first question here, this is regarding the iPhoneOS3 not MacOSX. I am fairly new to Objective-C and I’ve never developed in a environment without automatic garbage collection so I am a little confused by this. Here’s some valid code assigning a view controller to an app delegate from an example off Apple.com:
MyViewController *aViewController = [[MyViewController alloc]
initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
[self setMyViewController:aViewController];
[aViewController release];
So, from what I understand, I must release aViewController because it is first allocated (+1 = 1); then retained in the setter (+1 = 2); then released in the setter (-1 = 1); and then no longer needed so finally released again (-1 = 0) and the memory is freed. Wel could I not just skip assigning the temporary object aViewController and nest these functions like so:
[self setMyViewController:[[MyViewController alloc]
initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]]];
I was wondering if this would work correctly? I am a little worried since the setter requires a pointer-to-ViewController instead of just a copy of one. And since I am only passing a return value, is the pointer-to-ViewController in the setter going to point to data that may be erased or lost before it can assign it? I am sorry if this seems like a dumb question, but I am having a hard time finding an answer anywhere, and I am trying to establish good techniques for non-garbage collection environments. Thanks!
Don’t think of memory management in terms of absolute retain counts. Think of it entirely in terms of ownership and encapsulation.
When you
allocan object, you have created an object that you own. When you set that object as a value on another object, that other object should retain the object to express ownership. If your code is no longer interested in the object, you should thenrelease(orautoreleaseit if you want to return it to something else).To answer your specific question, the above line of code, by itself, will cause a memory leak assuming that
-setMyViewController:is implemented correctly.