开发者

Difference between viewDidUnload and dealloc function when I release the Object

I set a variable as IBOutlet. and use @property(retain) @synthesize in my .h and .m file. Like this:

@interface testViewController {

    NSArray *keys;

}

@property (nonatomic, retain) NSArray *keys;

@end

@implementation SectionViewController

@synthesize keys;

In many books, they set that object to nil in viewDidUnload method, and use release method to release that object in dealloc method. Like this:

- (void)viewDidUnload {
    self.keys = nil;
}


- (void)dealloc {
    [super dealloc];
    [keys release];
}

As I know, if I use self.keys = nil, the result is same as [keys release] in dealloc method;Object keys will be release, and "nil" will not be retain.

Why some books use this form every time?

开发者_如何学运维Thanks


First off, your -dealloc method will crash. You've put the call to [super dealloc] in the wrong spot. Calling [super dealloc] will cause your object to be freed, so any references to ivars after this call are referencing garbage memory. Instead you should rewrite this to be

- (void)dealloc {
    [keys release];
    [super dealloc];
}

Now to answer your question. It seems you want to know why people say self.keys = nil in some places, but use [keys release] in dealloc. There's a few good reasons. The first is that someone (a coworker, your self a few months from now, or a user if you open-source your code) may override the setter -setKeys:, either in this class or in a subclass. That setter may make assumptions about the state of the object that simply aren't valid in -dealloc (e.g. assuming that other ivars/properties still contain valid values). If assumptions like this are made, then it simply isn't safe to call the setter in -dealloc. Another reason that's harder to track down is someone may have an active Key-Value Observing registration on your object, for the key @"keys". Calling self.keys = nil will fire off a KVO notification, which is not something you want to do in dealloc. However, saying [keys release] will skip the KVO notification entirely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜