您应该在使用委托的类中还是在类本身中将委托设置为 nil [英] Should you set the delegate to nil in the class using the delegate or in the class itself

查看:13
本文介绍了您应该在使用委托的类中还是在类本身中将委托设置为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 A 类使用 B 类,A 类是 B 类的委托,如果委托在 B 类的 dealloc 中设置为 nil 可以吗?我看到代码通常在 A 类的 dealloc 中将委托重置为 nil,但不确定以一种或另一种方式执行此操作的真正区别.

If class A is using class B and class A is class B's delegate, is it ok if the delegate is set to nil in class B's dealloc? I have seen code usually resetting the delegate to nil inside class A's dealloc but wasn't sure the real difference doing it one way or the other.

例如这是通常的方式:

// somewhere in class A

- (void) someFunc {
  self.b = [[B alloc] init];
  self.b.delegate = self;
}

- (void) dealloc {
  self.b.delegate = nil;
  [self.b release];
}

推荐答案

是的,你应该在classA的dealloc中设置classB的delegate属性为nil.

Yes, you should set the classB's delegate property to nil in classA's dealloc.

这不是内存管理问题,因为应将委托属性标记为分配,而不是保留,以避免保留循环(否则将永远不会调用 dealloc).问题是,否则 classB 可能会在 classA 发布后向其发送消息.

It's not a memory management issue, because delegate properties should be marked assign, not retain, to avoid retain cycles (otherwise the dealloc will never be called). The issue is that otherwise classB might message classA after it has been released.

例如,如果 classB 有一个延迟调用说被隐藏",并且 classB 在 classA 之后被释放,它会向已经解除分配的 classA 发送消息,从而导致崩溃.

For example, if classB has a delagate call to say "being hidden", and classB is released just after classA, it would message the already dealloc'ed classA causing a crash.

记住,你不能总是保证 dealloc 的顺序,特别是如果它们是自动释放的.

And remember, you can't always guarentee the dealloc order, especial if they are autoreleased.

所以,是的,将 classA 的 dealloc 中的委托属性清零.

So yes, nil out the delegate property in classA's dealloc.

这篇关于您应该在使用委托的类中还是在类本身中将委托设置为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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