What happens if i call nsobject init more than once? Does it increase retain count?

孤街浪徒 提交于 2020-01-14 10:37:32

问题


I'm pretty new to Objective-C and i have lots of troubles with memory management and still i understand a little. If i have an object, NSArray * myArray for example, and i do this

myArray = [[NSArray alloc] initWithObjects:obj1,obj2,obj3,nil];

then i'm doing something and i want myArray to contain new objects and then i init it again

[myArray initWithObjects:obj4,obj5,obj6, nil];

seems like it does what i need but is it correct grom the point of view of memory management?does it increase retain count? should i release it twice then?


回答1:


Don't do that!

In general, if you want to reset the objects or things inside an already existing Objective C object, create and use some kind of Setter method.

For your array, again do not do this! The "initWithObjects" method you cite is a convenience to initialize a immutable (non-changeable) array with the items an array will be populated with over it's entire lifetime.

For what you are trying to do, just use NSMutableArray. The documentation for it is listed below:

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html




回答2:


It doesn't increase the retain count. The initial alloc sets the retain count to 1.

That said, you should never call an init method more than once on an object. While your example might work, at best it's probably leaking its internal storage and not releasing your obj1, obj2, and obj3. At worst, it could have inconsistent internal state and could lead to a crash.

If you're just doing this a couple times, you might as well create a new array:

NSArray* myArray = [NSArray arrayWithObjects:obj1, obj2, obj3, nil];
// Do some stuff...
myArray = [NSArray arrayWithObjects:obj4, obj5, obj6, nil];
// Do more stuff

If you're doing it a lot, e.g., in a loop, you should probably use an NSMutableArray:

NSMutableArray* myArray = [NSMutableArray array];
for (...) {
  [myArray removeAllObjects];
  [myArray addObject:obj4];
  [myArray addObject:obj5];
  [myArray addObject:obj6];
  // Do stuff
}



回答3:


It's the old question. But I have found similar answer by this link:

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#semantics-of-init

Little quote from the link:

It is undefined behavior for a program to cause two or more calls to init methods on the same object, except that each init method invocation may perform at most one delegate init call.



来源:https://stackoverflow.com/questions/8036569/what-happens-if-i-call-nsobject-init-more-than-once-does-it-increase-retain-cou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!