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

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

问题描述

如果A类使用B类,而A类是B类的委托,那么如果B类的dealloc中的委托设置为nil,那么它是否正常?我已经看到代码通常将代理重置为A类的dealloc中的nil,但不知道真正的区别是以某种方式进行。



这是通常的方式:

  //在类A的某个地方

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

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


解决方案

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



这不是内存管理问题,因为委托属性应该被标记为assign,而不是保留,以避免保留周期(否则dealloc永远不会被调用)。问题是,否则classB可能会在释放后消息classA。



例如,如果classB有一个叫做隐藏的delagate调用,并且classB被释放就在ClassA之后,它会发出已经被释放的classA导致崩溃的消息。



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



所以是的,没有在classA的dealloc中的委托属性。


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.

e.g. This is the usual way:

// somewhere in class A

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

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

解决方案

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

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.

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.

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

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

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

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