I am slowly teaching myself cocoa for the iPhone (via the Stanford Class on iTunes U ) and I just left through the memory management part and I would like to hope to get some confirmation that the assumptions I make about how the memory is processed and how [release] and [autoadvertising] work. Since memory management is really a basic and fundamental, but very important part of the programming experience, I would like to make sure that I am doing it right.
I understand that you need to free everything related to alloc, new or copy.
If I do this:
NSString *temp = [[NSString alloc] initWithString:@"Hello World"];
Then I need to add [temp release / autorelease] in the end, since I have alloc.
However, if I do this:
NSString *temp = @"Hello World";
Then it doesn't seem to need a release statement. Does the NSString class call automatically as part of the destination?
Also, is there a difference between the two temp objects here after these statements? They both contain the same string, but are there any memory / usage ways in which they differ?
Secondly, with properties, I assume that the abstract is processed automatically. If I have this:
@interface Person : NSObject { //ivars NSString *firstName; NSString *lastName; } //properties @property NSString *firstName; @property NSString *lastName; ///next file @implementation Person @synthesize firstName; @synthesize lastName; - (void) dealloc { //HERE!!!! [super dealloc]; }
I assume that I do not need to add [firstName release] and [lastName release] (in // HERE !!!!), since this is automatically handled by the properties. It is right?
I understand that if I do this in code (assuming I defined initWithFirstName):
Person *Me = [[Person alloc] initWithFirstName: @"Drew", lastName:"McGhie"];
that later I will have to use [Me release / autorelease];
Any help confirming or correcting my understanding is greatly appreciated.
RECORDING ANSWERS ANSWERS
I thought I would write all this by going through all the answers and testing the suggestions and telling about what worked.
I need to add [firstName release], [lastName release], but I also need to add (save) to the property descriptions. Do not add (save) triggered warnings, as it assumes (assign). This is how I finally set up the class
@interface Person : NSObject { //ivars NSString *firstName; NSString *lastName; } //properties @property (retain) NSString *firstName; @property (retain) NSString *lastName; ///next file @implementation Person @synthesize firstName; @synthesize lastName; - (void) dealloc { [firstName release]; [lastName release]; [super dealloc]; }