Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do they initialize pointers this way?

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.

like image 658
Rob Avatar asked Apr 15 '26 00:04

Rob


1 Answers

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.

like image 181
T . Avatar answered Apr 16 '26 15:04

T .



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!