正确释放一个viewController,将其设置为其他类的委托? [英] Release a viewController correctly that sets it self as delegate to other classes?

查看:81
本文介绍了正确释放一个viewController,将其设置为其他类的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的第一件事是创建一个ViewController并将其推送到导航控制器。

First thing i do is create a ViewController and push it to the Navigation Controller.

viewController = [[MyViewController alloc] init];
[navController pushViewController:viewController animated: NO];
[viewController release];

现在保留计数为2(pushViewController使用2保留显然但不是我的责任)到目前为止一切都很好。

Retain count is 2 now (pushViewController uses 2 retain apparently but not my responsibility) so far so fine.

在MyViewController中,我正在创建一个类的实例,并将ViewController设置为实例的委托。

Inside MyViewController i'm createing a instance of a class and sets the ViewController as delegate to the instance.

timer = [[MyBackgroundTimer alloc] initWithInterval:20];
[timer setDelegate:self];

现在viewControllers保留计数增加了1因为setDelegate:

Now the viewControllers retain count has increased by 1 becouse of setDelegate:

但是当我稍后发布viewController时,它永远不会调用dealloc因为我还有一个保留计数。

But when i'm releasing the viewController later it will never call dealloc becouse i have one more retain count.

你应该如何正确地删除当你把自己设为代表时保留计数?

How should you correctly drop the retain count when you set your self as delegate?

推荐答案

你的班级 MyBackgroundTimer 应该将委托属性设置为assign而不保留。

Your class MyBackgroundTimer should have the delegate property as assign and not retain.

@property (nonatomic, assing) id delegate;

此类应该在需要使用时保留委托,并在完成后释放。

And this class should retain the delegate just when it needs to use it, and release when it is done.

@implementation MyBackgroundTimer 

@synthesize delegate;

-(void) startTimer {

    [self.delegate retain];

    //... do some actions

}


-(void) timerStopped {

    //... call delegate methods

    [self.delegate release]

}

@end

请务必记住,可以将您的代理作为保留属性。但要以正确的方式这样做,你必须确保在调用dealloc之前释放它(如上例中的 timerStopped 方法)

It is important to remember that you can have your delegate as a retain property. But to do so the right way, you have to ensure that you release it before dealloc is called (like the timerStopped method in the example above)

我这样说是因为如果你尝试在dealloc方法中释放委托,那么实例化 MyBackgroundTimer 的类与委托是同一个类,并且它还在dealloc中释放 MyBackgroundTimer (这几乎是常见的情况),两个类的dealloc方法永远不会被调用,因为每个类都拥有另一个,导致内存泄漏(显示在仪器上)。

I say that because if you try to release the delegate at the dealloc method, the class that instantiates MyBackgroundTimer is the same class as the delegate, and it also releases MyBackgroundTimer at the dealloc (which is pretty much the common case), the dealloc method of both classes will never be called, as each class will have the ownership of the other, resulting in a memory leak (that will not be shown at instruments).

这篇关于正确释放一个viewController,将其设置为其他类的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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