Managing Literal Syntax Memory

  • There are three modes for creating an array variable:

    • NSArray *array = @[@0, @1];

    • NSArray *array = [NSArray arrayWithObjects:@0, @1, nil];

    • NSArray *array = [[NSArray alloc] initWithObjects:@0, @1, nil];

  • When I use the second mode to create, varialbe "array" will be sent to autoreleasepool; When I use the third, saveCount var will be 1, but will not be sent to autoreleasepool; I want to know that the first mode has the same effect with the second mode or third mode;

+5
source share
4 answers

The general rule is that if you did not call a method starting with "alloc" or "new" or containing "copy", then you do not own the object and have neither the right nor the responsibility to release it. Although, of course, if you explicitly save the object, then you need to balance it with the release (or autorelease, which is just another way to organize its release).

Do not try to talk about what objects may or may not be in the autorun pool. Also, do not try to reason about account hold. Just care about property rights and obligations.

+2
source

The result of the first and second modes is identical. The first mode is the convenient syntax of the second

Source: Objective-C Literals

+3
source

Always read the retention value as delta. So:

 1. NSArray *array = @[@0, @1]; 

array has +0 to save the counter (which it saved, and then autoreleased about the creation basically does not matter, and, in fact, it may not have been saved and autoreleased at all - NSString *foo = @"foo"; has exactly the same + 0, but implementation details are not saving / auto-advertising).

 2. NSArray *array = [NSArray arrayWithObjects:@0, @1, nil]; 

Same as (1), but with a thumb.

 NSArray *array = [[NSArray alloc] initWithObjects:@0, @1, nil]; 

array has a value of +1 to keep as much as possible. The only detail you need to know is that in order for your code responsibilities for array be rejected, this object must be release d or autorelease d. Was it created with +1 account retention ... does it have an internal retention rate of 42 ... regardless of whether it was saved 5 times and auto-implemented 4 .... they all have nothing to do with your code.

+1
source

Besides the details of memory allocation, there is one big difference between

 NSArray* array = @[obj1, obj2, obj3]; 

and

 NSArray* array = [NSArray arrayWithObjects: obj1, obj2, obj3, nil]; 

The second will be stopped with the first argument nil. You expect an array with three elements, but if obj1! = Nil and obj2 == nil, then the result will be an array with one element. The first throws an exception if any of obj1, obj2 or obj3 is nil.

+1
source

All Articles