Tuesday, January 11, 2011

iPhone - when is dealloc for a viewcontroller called?

When an object's retain count hits 0 it is marked by the run time for cleanup. When the run time cleans up the object and reclaims the memory, dealloc is called giving it a chance to clean any other object references to instance variables or the like. Does that help? If you want to see it called, put
NSLog(@"%s", _cmd);
or a break point at the beginning of your dealloc method and watch the debugger/console..




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.)

1 comment:

  1. nice 1 dude ..... add some extra stuff like when dealloc of viewController get called

    ReplyDelete