开发者

View controller release before delegate return

开发者 https://www.devze.com 2023-02-28 05:44 出处:网络
I have a problem. My view controller (ViewController) implement a delegate method of a object (DataPuller, data get from the internet). DataPuller will retrieve dat开发者_Python百科a on the internet w

I have a problem. My view controller (ViewController) implement a delegate method of a object (DataPuller, data get from the internet). DataPuller will retrieve dat开发者_Python百科a on the internet without blocking user interaction with the view. But when I navigate between screen, in some cases, that ViewController release before DataPuller return the list of objects. The DataPuller return, it checks:

if (delegate && [delegate respondsToSelector:@selector(getCommentDidDownloadFinish:)]) {
    [self.delegate performSelector:@selector(getCommentDidDownloadFinish:) withObject:self];
}

And the application crash here because ViewController release, it becomes a zombie object. Does anyone have this problem before and how to solve it? I think another way is using NSNotification, but I wonder any other better solutions. Any ideas, solutions are welcomes. Thanks.


Your view controller must remove itself as the DataPuller delegate at some point. Typicially, this is handled in the dealloc method:

- (void)dealloc {
     dataPuller.delegate = nil;
     [dataPuller release];
     [super dealloc];
}

You may also decide to do this in -viewDidUnload or -viewDidDisappear:.


Delegation (usually) implies some sort of ownership - i.e., if you make an object a delegate of another object, usually the delegate object holds a strong reference (i.e., retains) the delegating object.

As an example, a UITableViewController is the delegate of its UITableView. This is okay, because the controller retains the tableview through the "view" property.

If your design does not allow ownership, use notifications, like you already suggested. As a bonus, notifications can signal multiple listeners if you would ever need that.

Don't forget to remove your observer in the dealloc of the view controller!

0

精彩评论

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