何时将委托设置为 NULL

发布于 2024-11-07 19:05:50 字数 807 浏览 0 评论 0原文

我在这里读到了一个提示 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我三岁 2024-11-14 19:05:50

如果执行委托的对象可能会保留在其他地方,并且您没有将委托设置为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文