开发者

Release a viewController correctly that sets it self as delegate to other classes?

First thing i do is create a ViewController 开发者_Go百科and push it to the Navigation Controller.

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

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

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];

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

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?


Don't retain your delegate. If you're using a property, define your delegate as assign, not retain. Somebody else needs to retain your delegate, not you.


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

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)

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜