Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is dealloc in objective C

Tags:

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?

like image 961
Questions Avatar asked Jul 16 '10 06:07

Questions


1 Answers

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

like image 58
John Franklin Avatar answered Oct 22 '22 00:10

John Franklin