navigationController popToRootViewController and viewWillDisappear
I have a simple navigation hierarchy:
Controller 1 > Controller 2 > Controller 3
Each controller contains a reference (@property (nonatomic, assign) ...
) to it's child and parent.
My viewWillDisappear looks something like this:
- (void)viewWillDisappear:(BOOL)animated {
NSLog(@"%s", __FUNCTION__);
if (![self.navigationController.viewControllers containsObject:self]) {
// View has been pop开发者_运维百科ped! Important to distinguish between view popping and tab switching.
// If parent view controller is active, pass a message.
if (_refParentViewController && !_isSearchViewController) {
_refParentViewController.valueX = @"xyz";
}
}
[super viewWillDisappear:animated];
}
Now, there's a case where following statement is executed (by Controller 1):
[self.navigationController popToRootViewControllerAnimated:NO];
As a result, i get a crash because _refParentViewController is a deallocated instance (at this point). How can i check whether _refParentViewController is valid? I thought that the view controllers/views will get destroyed in order but it appears that there isn't any specific order and Controller 2 is destroyed before Controller 3.
I can check retainCount
but i'm not sure if that's a good idea.
I can check retainCount but i'm not sure if that's a good idea.
It is a horrible idea; retainCount is useless, don't call it. And note that retainCount can never return 0; it can't be used to know if an object is deallocated or not.
If both your parent and child properties are assign
, then who is responsible for retaining the view controller? You need a retain
that spans the expected lifespan of the parent/child properties.
I would suggest that you make the child
property retain
and leave the parent property as assign
. You also need to make sure that when you set the child
to nil
(which, with a retain
property will release
it as long as you go through the property's setter) that you first set the child's parent
property to nil
.
精彩评论