代理 - 保留或分配 - 释放? [英] Delegates - retain or assign - release?

查看:99
本文介绍了代理 - 保留或分配 - 释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多与代表相关的文章,我想知道正确的方法来参考。假设我有一个对象声明为:

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

通过 MyViewController ,它将调用其委托的方法来响应与用户的交互。

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

当是时候摆脱<$ c $的实例c> MyViewController ,委托是否需要 release

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?

或者相反,应该委托甚至保留?也许应该 @property(nonatomic,assign)id delegate ?根据 Apple的文档

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


retain ...您通常将此属性用于标量类型(如NSInteger和CGRect),或者(在引用计数的环境中)例如代理。

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?

推荐答案

你通常要分配代理,而不是而不是保留它们,以避免循环保留计数,其中对象A保留对象B,对象B保留对象A.(您可能会看到这称为保留对委托的弱引用。)例如,考虑以下常见模式:

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];
}



<和 self 声明使用 retain 现在保留 self.utilityObject self.utilityObject 保留 self

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

查看为什么Objective-C委托通常给予属性assign而不是retain?以获取更多信息。

如果你分配委托而不是保留它,那么你不需要担心在dealloc释放它。

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

这篇关于代理 - 保留或分配 - 释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆