autorelease vs. release in dealloc - objective-c

I know memory management in iOS is tricky subject to newbies like me, but I was hoping for a clear explanation here on stackoverflow which I could not find anywhere else.
So, pretend I have a property / ivar
#property(nonatomic, retain) UIPopoverController *popOver;
which I'm allocating like this:
self.popOver = [[[UIPopoverController alloc] initWithContentViewController:popOverContent] autorelease];
Now, in my dealloc and viewDidUnload methods, I do both
// in viewDidUnload:
self.popOver = nil;
// in dealloc:
[popOver release];
Question:
If I do nil / release in viewDidUnload / dealloc, do I really need to autorelease at allocation?
Vice versa, if I do autorelease at allocation, do I need to nil / release later?
What's the difference, if any?
Thanks in advance for your time - I'll continue reading, seriously memory management can't be that hard to wrap your head around...

Don't be confused by the autorelease in this line:
self.popOver = [[[UIPopoverController alloc] initWithContentViewController:popOverContent] autorelease];
After this statement you effectively own the object because the property setter claimed ownership of it. The autorelease balances the alloc-init.
So... yes, you need to autorelease at allocation. If you did this (no autorelease), you would leak:
self.popOver = [[UIPopoverController alloc] initWithContentViewController:popOverContent];
Another option is to use a temporary variable instead of autorelease:
UIPopoverController *temp = [[UIPopoverController alloc] initWithContentViewController:popOverContent];
self.popOver = temp;
[temp release];
Either way you need to release the object in dealloc.

1 If I do nil / release in viewDidUnload / dealloc, do I really need to autorelease at allocation?
Yes.
2 Vice versa, if I do autorelease at allocation, do I need to nil / release later?
Yes.
In the first case, the auto-releasing is done on behalf of that method. That method doesn't need the popover anymore, so it needs to (auto)release it.
At dealloc, your object doesn't need the popover anymore. Therefore, you need to release it.
It's very simple. You don't have to consider long-term object ownership; you just need to think very locally, at the level of every method. The decision of releasing it or not doesn't at all depend on whether that object is kept by some other parts of the program. In a method, if you alloc an object and you no longer need it in that method, you (auto)release it.
The dealloc is a slight exception to the rule. There, you need to release the ownership of all the instance variables.
That's it!

Yes. But maybe not in this case.
Yes. But maybe not in this case.
viewDidUnload is called when the the view is unloaded, dealloc is called when the view Controller is being destroyed.
In viewDidUnload you release objects that are used by the view that are not needed anymore and can be recreated in viewDidLoad. Obvious, since the view is not being displayed it doesn't need to hold on to the objects that are set up by the view controller for it.
In dealloc you are cleaning up the viewController and here you clear up all it's resources, including those that it has assigned to the view.
In this case, the view does not own the popover controller - it should be owned by the view controller, so there is no need to release it in viewDidUnload but you do need to release it in the dealloc.

Related

How to release Instance variables?

I have a doubt that how we will release the instance variables properly.I know we can do the release in the dealloc method. If we are given as self.instancevariouble=nil in the viewdidunload also will release the object. My question is If there is any problem if we are given the object as nil in the unload method and then also release it in the dealloc method. Also how do I need to release a tableview which is added as IBoutlet in the xib.Can anybody point me in the right direction?
There is no problem with calling release on a nil object but, as a better strategy, move to ARC and most of these concerns will just go away. (Also note that iOS 6 does not unload views.)
If you try to release a nil object it will "work". You can send a message to a nil object without the app crash ;) so you can do this :
UILabel *lbl = nil;
[lbl release];
It won't do anything.
And about "How i need to release a tableview which is added as IBoutlet in the xib.Can anybody point me in the right direction?" You have to "connect" your UITableView in the xib file with your code and do a :
[myTableView release];
If you use self.instanceVariable = nil in the viewDidUnload method (which by the way does no longer get called in iOS 6) the value is of course nil. So if you then release that in the dealloc method you basically call [nil release]; and that does nothing.

UIViewController pushViewController high retain count of View controller

I wrote the following piece of code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
GameViewController *gameViewController = [[GameViewController alloc]initWithLevelNumber:([levelGroup intValue]*100+indexPath.row) Bonus:NO];
NSLog(#"Retain Counter =%d",gameViewController.retainCount);
[navController pushViewController:gameViewController animated:YES];
[gameViewController release];
NSLog(#"Retain Counter=%d",gameViewController.retainCount);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
The results of the two logs are, in sequence 1 and 6!
How this is possible? I only call the alloc method one time and release after push the controller on the stack.. alloc-> +1, push-> +1, release-> -1 = 1 or not?
I'd like the view controller is dealloc'd when i pop it off the stack..
Please read this note to be clear in this question. It is part of NSObject Protocol Reference:
Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.
NSObject Protocol Reference. RetainCount discussion
Autorelease your GameController creation, like this:
GameViewController *gameViewController = [[[GameViewController alloc]initWithLevelNumber:([levelGroup intValue]*100+indexPath.row) Bonus:NO] autorelease];
Then delete [gameViewController release]; Then your code looks kosher, and gameViewController will be autoreleased after being popped from the nav stack. Don't worry about retainCount - when you push a view controller, UIKit takes over and will retain/release the thing as needed. You just have to worry about your code. Actually, the way you have it written should be fine, I just think my suggestions here make the code cleaner.
Unless you see in Instruments that you have a memory leak of your gameViewController object, I think you needn't worry.
It's because there is some retain internally (by pushViewController: method), you should not check the retain count, only check that you release the object you own, especially when you check retain count between sdk call methods.
Do you use NSNotificationCenter in your GameViewController?
May be you add your view controller as observer to NotificationCenter and it increase retainCount.

Easy pattern for releasing properties

I have a general question regarding memory management of properties. Currently, I always use properties without any explicit declaration of related ivars. And, for every retained or copied property I'm releasing its retain count both in dealloc and viewDidUnload methods:
-(void)dealloc{
[self.myProperty release];
[self.myOutlet release];
[super dealloc];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myProperty = nil;
self.myOutlet = nil;
}
Now, I know that only the outlets and properties retained by the main view should be set to nil in viewDidUnload, and the rest properties should be released in dealloc. But hey, why do I have to bother for every property where it must be released - in dealloc or in viewDidUnload? If some property will be released twice it's OK because it wouldn't crash the app by sending a message to nil object. Putting release in both places (dealloc and unload) saves time and prevents from bugs later when doing code refactoring and forgetting to change release place. Any critics and shouting on that? :)
If you're using property accessors in -dealloc because you don't have access to the ivar directly, you should do the same in -dealloc that you do in -viewDidUnload:
self.myProperty = nil;
The point of using -release in -dealloc is to avoid calling the accessor, which conceivably could have been overridden by a subclass to have side effects that you don't want in -dealloc, when everything else from the subclass has already been deallocated. But if you're already calling the accessor in -dealloc, you might as well use the setter to release the ivar and ensure that it's done right.
The difference between -dealloc and -viewDidUnload is that you're still working with a complete, fully functional object in -viewDidUnload, whereas the object may already be partially deallocated in -dealloc.
My previous answer on this discusses what Apple recommends and why. Relevant portions reproduced here for clarity:
Also, from the Apple docs on -viewDidUnload:
The preferred way to relinquish ownership of any object (including those in outlets) is to use the corresponding accessor method to set the value of the object to nil. However, if you do not have an accessor method for a given object, you may have to release the object explicitly
So, there you go. If your outlet has a property associated with it (which they all should anymore), then nil it in -viewDidUnload -- but don't release it. This makes sense when you consider what is actually happening in a synthesized accessor; the code looks something like this:
- (void) setMyView1 : (UIView *) view {
if (myView1) // the associated IVAR is already set
[myView1 release];
myView1 = [view retain];
}
As you can see, setting a synthesize property to nil implicitly releases the retained object.
Also from the docs in regards to -dealloc:
If you implement this method but are building your application for iOS 2.x, your dealloc method should release each object but should also set the reference to that object to nil before calling super.
Unless you are supporting iOS2.x, there is no need to set objects to nil in dealloc.
So, to summarize Apple's docs regarding -viewDidUnload and -dealloc:
In -viewDidUnload, nil properties (including IBOutlet properties), but don't release them
In -dealloc release properties, but don't nil them (unless building for 2.x).

What is dealloc in objective C

I want to ask an general question about the objective C. When I write the program of the iPhone application, I always see a function called 'dealloc' in the .m. when will this method be called? do I need to put all the [release] in here good for the application? thank you very much.
// ------------------ updated content -------------------------
NSArray *arr;
NSString *str;
NSMutableArray *mutableArr;
// in the dealloc
// it should have to following
[arr release];
[str release];
[mutableArr release];
the function will be call 3 times?
The dealloc method is called on an object when it's retain count has reached zero. Retain counts are increased by one for each retain call, and reduced once for each release call. The autorelease schedules a future release call when the current NSAutoreleasePool is drained, typically at the end of an event cycle, but you can set up your own NSAutoreleasePools on memory intensive operations. (See the NSAutoreleasePool docs for details.)
What should you put into dealloc? You should put a release for each member object the object of that class retains.
A couple things make this easier. The nil object will quietly ignore any messages sent to it, so [foo release] when foo = nil is not a bug. However, releasing an object twice can cause serious issues. My (hardly unique) solution to this is to explicitly set whatever I just released to nil, whenever I release it. In fact, I put the nil assignment on the same line as the release so I can grep for "release" and find places I missed. Example:
#interface MyClass {
Foo *foo;
Bar *bar;
NSInteger baz;
}
-(void)dealloc;
#end
#implementation MyClass
-(void)dealloc {
[foo release]; foo = nil;
[bar release]; bar = nil;
[super dealloc];
}
#end
I'll assign nil to a variable even when that variable is about to go out of scope or the object is about to go away. Why? If another object of the same class is allocated in the same memory space after I've released this one, it guarantees there will be no dangling pointers the new object might accidentally use and make debugging a nightmare. (See also NSZombieEnabled for debugging help.)
when will this method be called?
It's called when the reference count for that object becomes 0 because all its pointers have been released. The memory taken up by it is deallocated (freed); the object itself is destroyed.
do I need to put all the [release] in here good for the application?
Yes, release all the properties of the object that are still retained.
EDIT: in response to your updated question, dealloc in your custom object is only called once. It will then send these three messages:
[arr release];
[str release];
[mutableArr release];
To each of the three objects. They are entirely different objects, but if you only have one instance of each, then their reference counts all go down to 0 and their dealloc methods are called automatically.
As you surmised, it's called when an object is destroyed. The object should release everything it owns.
In Other words, Dealloc frees/destroys/releases the memory you allocated to your objects.
Allocated objects to memory should be destroyed once not used to avoid memory leaks that might cause your application to crash.
ZaldzBugz

Few questions: Lifecycle of UIViewController; release vs setting to nil

I have a couple of questions relating to UIViewController:
1) When are each of the methods called for UIViewController? Specifically, the difference between viewDidLoad, viewDidUnload, and dealloc.
2) What's the difference, in general, when setting a pointer equal to nil and releasing the pointer? I know that in viewDidUnload you're supposed to set it equal to nil but in dealloc call release.
UPDATE: Sorry, just realized the question is misleading. Instead of dealloc, I meant -- when is initWithNibName:bundle: and release called? Just once by IB, right?
Setting a pointer to nil doesn't release the memory that it points to.
When you do something like
self.pointer = nil;
it's usually a case that the property has a retain attribute. When this is the case, setting the property to nil will indirectly cause a
[pointer release];
pointer = nil;
In the case of the view controller methods, viewDidLoad is called when your view is loaded, either from a nib, or programatically. More specifically, it's called just after -loadView is called. You shouldn't need to call loadView manually, the system will do it. The viewDidUnload method is called in the event of a memory warning and your view controller's view is not onscreen. Subsequently, loadView and viewDidLoad will get called again on demand.
The dealloc method, as normal, is called when your object's retain count reaches 0.
pointer = nil; // just clears the variable in which you store the pointer, but does not free memory.
[pointer release]; // just frees the object (memory), but does not clear the variable used to point to it.
self.pointer = nil; // sets the variable to nil. Also releases the object ONLY if pointer is a #property(retain) ivar.
One easy way to see when various methods are called is to do this in your UIViewController:
- (void)viewDidLoad
{
NSLog(#"MyViewController::viewDidLoad");
[super viewDidLoad];
// the rest of your viewDidLoad code, here.
}
// Etc., for the other methods of interest.
NOTE: much can be gleaned from overriding retain & release to log and then following along in the debugger.