Why do they initialize pointers this way?

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-05-04T12:55:09Z Indexed on 2010/05/04 12:58 UTC
Read the original article Hit count: 183

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];
        myString = tempString;
        [tempString release];
    }
    return self;
}

Why can't I just do the following?

-(id)init {
    if (self = [super init]) {
        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.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone-sdk