iPhone ivars vs using self: don't need autorelease? [duplicate]
Possible Duplicate:
U开发者_运维百科se autorelease when setting a retain property using dot syntax?
What is difference between using ivars and self. notation?
instanceVar is instance variable declared with retain.
1) instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"]; //do I need autorelease here?????
2) self.instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"] autorelease];
Also, Do I need autorelease in the first situation?
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;
1) instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"]; //do I need autorelease here?????
The NSmutableArray is created with a retain count of 1, you need to release your instanceVar in your dealloc()
method
2) self.instanceVar = [[NSMutableArray alloc] initWithObjects:@"1", @"2"] autorelease];
Here you are using the setter, and since it is declared with retain
it will increase its retain count by 1, the alloc init already increased the retain count by 1, so the total retain count is 2. However the autorelease msg will decrease this by 1 probaby in the next run loop. So again you only have to release this on your dealloc()
method.
In the first situation you probably DO NOT want to autorelease, since this is an IVar you will probably want to use it again, and if you autorelease
it the retain count will be 0 soon (most likely in the next run loop)
精彩评论