Why do they initialize pointers this way?
- by Rob
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.