This is explained in multiple places but seems as you asked what the different is
The first call is unchanged and looks like this:
instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"];
The second call when compiled will look something like this (assuming you have used a @property
with retain
and @synthesize
:
self.instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"];
// The previous line will compile to this next line
[self setInstanceVar:[[NSMutableArray alloc] initWithObjects:@"1", @"2"]];
The body of the - (void)setInstanceVar:(NSMutableArray *)instanceVar;
method will look something like this (the compiler create this for you because of your @property
and @sythesize
):
- (void)setInstanceVar:(NSMutableArray *)anInstanceVar
{
if (instanceVar != anInstanceVar) {
[instanceVar release];
instanceVar = [anInstanceVar retain];
}
}
Therefore in the call
self.instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"];
You have the +1 retain count on the newly created NSMutableArray
and then you have the +1 retain count added from going through the setter.
This means that you require the extra release to match retains you are taking. It is considered better to not use autorelease
in iPhone so you can be sure memory is being freed when you want it to. Therefore you should normally take the pattern
- Create local var
- Assign local var to ivar through setter
- release local var
Which looks like this (FIXED thanks to @jamapag)
NSArray *tmpMyArray - [[NSArray alloc] initWithObject:@"Hello"];
self.myArray = tmpMyArray;
[tmpMyArray release]; tmpMyArray = nil;