What happens if I call nsobject init more than once? Does retention increase?

I am new to Objective-C and I have a lot of memory management issues and I still understand a little. If I have an object like NSArray * myArray and I do this

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

then I am doing something and I want myArray to contain new objects and then initialize it again

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

it looks like it is doing what I need, but is this true in terms of memory management? Does retention increase? Should I release it twice?

+4
source share
3 answers

Do not do this!

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

For your array, do not do this again! The initWithObjects method you are quoting is a convenience for initializing an immutable (immutable) array with elements that will be filled by the array throughout its life.

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

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

+4
source

This does not increase the number of deductions. The initial alloc sets the hold value to 1.

However, you should never call the init method more than once on an object. Although your example may work, at best it probably obj3 in the internal storage and does not release your obj1 , obj2 and obj3 . In the worst case, it may have an inconsistent internal state and may lead to failure.

If you do this just a couple of times, you can 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 do this a lot, for example in a loop, you should probably use NSMutableArray:

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

This is an old question. But I found a similar answer from this link:

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

A small quote from the link:

This undefined behavior for a program calls two or more init calls on the same object, except that each init method call can make at most one init init call to the delegate.

+2
source

Source: https://habr.com/ru/post/1379990/


All Articles