I'm just starting to learn Objective-C. I read the Cocoa Become an XCoder book, and I think I learned the basics. Now, I'm following an online tutorial where I encountered this bit of code:
@synthesize name;
- (IBAction)changeGreeting:(id)sender {
self.name = textInput.text;
NSString *nameString = name;
if([nameString length] == 0) {
nameString = @"Cartman";
}
NSString *greeting = [[NSString alloc]
initWithFormat:@"Hello, my name is %@!", nameString];
label.text = greeting;
[greeting release];
}
My question here is, shouldn't we call 'release' also on the *nameString variable? Or by doing that I would clean also the 'name' property which should be released in the 'dealloc' method? Cause if I understand correctly, I must call 'release' on all variables located inside functions at the end of those functions, but on the class properties I must call 'release' only in the 'dealloc' method?
Thanks
Release only the objects you claim ownership on. This means every property you set to retain or copy. Don't release assigned properties.
You claim ownership by sending alloc, copy, new or mutableCopy. Have a look at Apple's Memory Management Programming Guide / Object Ownership and Disposal. You should also release if you retain manually by sending retain.
Regarding this you don't have to release nameString.
greeting is released because you allocated it. nameString doesn't need to be released because it is an assignment. You have to release an object that you alloc as a general rule of thumb.
See the great Apple Memory Management Guide for further help. Memory management is a big hurdle for lots of iOS beginners, and the memory management guide should basically be required reading.
Also, in this specific example, you don't really need the nameString variable, you could just use self.name everywhere it is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With