views:

85

answers:

2

In almost all of the books I read and examples I go through I see pointers initialized this way. Say that I have a class variable NSString *myString that I want to initialize. I will almost always see that done this way:

-(id)init {
    if (self = [super init]) {
        NSString *tempString = [[NSString alloc] init];
        self.myString = tempString;
        [tempString release];
    }
    return self;
}

Why can't I just do the following?

-(id)init {
    if (self = [super init]) {
        self.myString = [[NSString alloc] init];
    }
    return self;
}

I don't see why the extra tempString is ever needed in the first place, but I could be missing something here with memory management. Is the way I want to do things acceptable or will it cause some kind of leak? I have read the Memory Management Guide on developer.apple.com and unless I am just missing something, I don't see the difference.

+4  A: 

The second example is correct.

Assuming that myString is an ivar, the first example is actually wrong because it leaves myString with a dangling pointer (a pointer to a deallocated object). If it were self.myString that would be a different story.

Tom Dalling
Doh...you are correct, let me modify the original. So there really is no difference between the two?
Rob
@Rob: now the 2nd code has memory leak.
KennyTM
+5  A: 

If self.myString is a retained property, the second example has to be

-(id)init { 
    if (self = [super init]) { 
        self.myString = [[[NSString alloc] init] autorelease]; 
    } 
    return self; 
} 

or it will leak. I can only assume this is the case and the first example simply wants to avoid using autorelease.

Toon Van Acker
So without autorelease, is the retain count 2 at the end?
Rob
Yup, `+1` for alloc and `+1` for the retained property.
Toon Van Acker
Perfect! Makes complete sense now thanks...
Rob