Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Beginner (release) question

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

like image 516
Hidden Avatar asked Jan 31 '26 11:01

Hidden


2 Answers

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.

like image 150
Nick Weaver Avatar answered Feb 03 '26 04:02

Nick Weaver


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.

like image 22
Jesse Naugher Avatar answered Feb 03 '26 05:02

Jesse Naugher