In the iPhone objective-c world, I’ve seen this pattern everywhere and I use it myself all the time without really understanding what is going on:
In Test.h
@interface Test: UIViewController
{
NSMutableArray *testArray;
}
@property (retain, nonatomic) NSMutableArray *testArray;
And in Test.m
@implementation Test
@synthesize testArray
- (void) viewDidLoad
{
// why do we do this?
NSMutableArray *init = [[NSMutableArray alloc] init];
self.testArray = init;
[init release];
[self.testArray addObject: @"A"]; // why can't I do this directly?
...
}
- (void) dealloc
{
[testArray release];
[super dealloc];
}
My question is: if testArray has a retain on it when it’s declared in the property, why do we need to create a new NSMutableArray init object, assign that to testArray and release? Why can’t I just start using testArray in viewDidLoad without doing anything else?
I know there’s some debate over the best way of doing this (creating a new object, or using an autorelease object), but in both cases, we end up with testArray with a retain count of 1. Which I believe the ‘retain’ property already gives it. So why the need to create this init object?
The ‘retain’ property doesn’t automatically create an NSMutableArray for you. Rather, it simply indicates that whenever you do assign something to that property, it will be retained.
If your code were this:
Then self.testArray would be
nil, and thus it would be essentially a no-op. Until you assign something to self.testArray, it’s empty.Here’s what’s going on.