Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

ios - Delegates - retain or assign - release?

I've seen a number of posts related to delegates, and I would like to know the proper way to reference them. Suppose I have an object declared like:

@interface MyViewController : UITableViewController {
    id delegate;    
}
@property (nonatomic, retain) id delegate;
@end

Through the lifecycle of MyViewController, it will make calls to methods of its delegate in response to interaction with the user.

When it's time to get rid of an instance of MyViewController, does the delegate ivar need to be release'ed in the implementation's dealloc method since it is declared with retain?

Or conversely, should delegate even be retained? Perhaps it should be @property (nonatomic, assign) id delegate? According to Apple's docs:

retain ... You typically use this attribute for scalar types such as NSInteger and CGRect, or (in a reference-counted environment) for objects you don’t own such as delegates.

Normally I'd just go with what the docs say, but I've seen a lot of code that calls retain on a delegate. Is this just "bad code?" I defer to the experts here... What is the proper way to handle this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You generally want to assign delegates rather than retain them, in order to avoid circular retain counts where object A retains object B and object B retains object A. (You might see this referred to as keeping a "weak reference" to the delegate.) For example, consider the following common pattern:

-(void)someMethod {
    self.utilityObject = [[[Bar alloc] init] autorelease];
    self.utilityObject.delegate = self;
    [self.utilityObject doSomeWork];
}

if the utilityObject and delegate properties are both declared using retain, then self now retains self.utilityObject and self.utilityObject retains self.

See Why are Objective-C delegates usually given the property assign instead of retain? for more on this.

If you assign the delegate rather than retaining it then you don't need to worry about releasing it in dealloc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...