How a view controller know when it is dismissed or popped out of the navigation controller stack?
My view controller needs to know when it is popped out of the 开发者_StackOverflow社区navigation controller stack, so that it can retain itself, wait and release itself later with another notification.
I intend to do like that when the view is sent dealloc message:
- (void)dealloc {
if (self.isPerformingSomeTask) {
self.isPopedOut = YES;
[self retain];
return;
}
[super dealloc];
}
But I think this is not a good solution?
This is an extremely bad idea.
- "-dealloc" is not the place to retain the object that is deallocated. If you want to be absolutely sure, that your object is not deallocated, then retain it upon construction, e.g. in "-viewDidLoad"
- "-dealloc" is not a way to detect that a view is popped from the navigation stack. You could be deallocated for any reason or the deallocation could be delayed even though you were popped from the stack
- If you want to detect, that the view is not displayed anymore, you should look for "-viewWillDisappear:"
- The pope has nothing to do with it, so don't pope out your views :-)
- If you need some object to receive the results of a long running task, probably your AppDelegate is a better receiver, not the view controller
EDIT: The following code refers to my comment below:
So you code should look like this
- (void) startMyLongTask {
[self retain];
// start the task
}
- (void) longRunningTaskReturns {
// process results
[self release];
}
- (void) dealloc {
// as long as longRunningTaskReturns is not called
// you will never come here
[super dealloc];
}
精彩评论