何时将委托设置为 NULL
我在这里读到了一个提示 SO 最佳实践发布:
“如果您将自己作为委托传递给另一个对象,请在释放之前重置该对象的委托。” 示例:
- (void)dealloc {
if (self.someObject.delegate == self) {
self.someObject.delegate = NULL;
}
self.someObject = NULL;
[super dealloc];
}
听起来很合理,但我不确定在什么情况下需要这样做。 例如,我有一个如下所示的视图控制器:
- (void) viewDidLoad {
myTextField.returnKeyType = UIReturnKeyDone;
myTextField.delegate = self;
}
在这种情况下我是否(应该)将委托设置为 NULL,例如:
- (void) dealloc {
if (self.myTextField.delegate == self) {
self.myTextField.delegate = NULL;
}
[myTextField release];
[super dealloc];
}
I read a tip here in a SO best practices posting:
"If you're passing yourself as a delegate to another object, reset that object's delegate before you dealloc."
EXAMPLE:
- (void)dealloc {
if (self.someObject.delegate == self) {
self.someObject.delegate = NULL;
}
self.someObject = NULL;
[super dealloc];
}
Sounds reasonable, but I'm not sure in what cases I need to do that.
For example, I have a view controller like the one below:
- (void) viewDidLoad {
myTextField.returnKeyType = UIReturnKeyDone;
myTextField.delegate = self;
}
Would I (Should I) set the delegate to NULL in that case, for example:
- (void) dealloc {
if (self.myTextField.delegate == self) {
self.myTextField.delegate = NULL;
}
[myTextField release];
[super dealloc];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果执行委托的对象可能会保留在其他地方,并且您没有将委托设置为 nil,则您的对象有可能在
dealloc
之后被调用,这将表现为崩溃。在这种特殊情况下,你可能没问题,但这样做肯定不会有什么坏处。If the object doing the delegating could be getting retained somewhere else and you don't set the delegate to nil there's a chance that your object could be called after it's
dealloc
, which would manifest as a crash. In this specific case you'd probably be okay, but it certainly won't hurt anything to do this.