there are three modes to create 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, the varialbe"array" will be throwed to autoreleasepool; When I use the third, the retainCount of var will be 1 but won't be throwed to autoreleasepool; I want to know the first mode has the same effect With The second mode or the third mode;
The result of the first and second mode is identical. The first mode is a convenience syntax of the second
Source: Objective-C Literals
The general rule is that if you didn't invoke a method starting with "alloc" or "new" or containing "copy", then you don't own the object and have neither the right nor responsibility to release it. Although, of course, if you explicitly retain an object then you do have to balance that with a release (or autorelease, which is just is another way of arranging to release it).
Do not try to reason about what objects may or may not be in the autorelease pool. Also, don't try to reason about retain counts. Just concern yourself about ownership rights and responsibilities.
Always consider the retain count as a delta. So:
1. NSArray *array = @[@0, @1];
array
has a +0 retain count (that it has retained and then autoreleased on creation is largely irrelevant and, in fact, it might not have been retained and autoreleased at all -- NSString *foo = @"foo";
has the exact same +0 semantics, but the implementation details are not a retain/autorelease).
2. NSArray *array = [NSArray arrayWithObjects:@0, @1, nil];
Same as (1), just with more finger exercise.
NSArray *array = [[NSArray alloc] initWithObjects:@0, @1, nil];
array
has a +1 retain count as far as you are concerned. The only detail you need to know is that for your code's responsibilities for array
to be relinquished, that object must be release
d or autorelease
d. Whether it was created with a +1 retain count... whether it has an internal retain count of 42... whether it was retained 5 times and autoreleased 4.... all are entirely irrelevant to your code.
Apart from 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 one will stop at the first nil argument. You expect an array with three elements, but if obj1 != nil and obj2 == nil then the result is an array with one element. The first one throws an exception if any of obj1, obj2 or obj3 is nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With