views:

97

answers:

2

Is there a way to know that a view controller is somewhere in the view controller lifecycle between -viewWillAppear and -viewWillDisappear?

I ask because I want to be damned sure that a method isn't fired when my view is either not on screen, or is about to disappear from the screen. When the view is about to disappear from the screen, certain objects which I cannot explicitly check at runtime may or may not be deallocated, so, obviously, interacting with them can lead to message sent to deallocated instance errors.

At present, I'm keeping track with a BOOL, like so:

- (void)viewWillAppear:(BOOL)animated {
    isOnScreen = YES;
    [super viewWillAppear:animated];
}

- (void)willWillDisappear:(BOOL)animated {
    isOnScreen = NO;
    [super viewWillAppear:animated];
}

And my method looks like this:

if (isOnScreen) [self doSomething];

Is there a simpler way to do this?

A: 

Use viewDidDisappear

- (void)viewDidDisappear:(BOOL)animated {
    // Do stuff that has to be done when this view is off screen.
}
coneybeare
I'm afraid I may have been unclear. I don't want to do stuff when the view is off screen, I want to do stuff when the view is on screen or is not about to be removed from the screen. For this reason, I'm setting `isOnScreen` true when the view controller will appear (the `doSomething` method is okay to be called) and setting it false when the view controller will disappear (the method can no longer be called until the view is about to reappear).
David Foster
+1  A: 

your way seems to be the simplest approach, if not the most robust. (simply checking if that instance of the view exists seems like the correct approach (if it hasn't been dealloced yet)).

I also don't REALLY understand the purpose of this, unless you have another view controller running methods that pertain to the view controller being showed that you are using the boolean for. In that case, its more a design problem than an upkeep problem.

Jesse Naugher
I can appreciate that the way I have described this could lead anyone to believe I have serious design problems. Basically, I have an MKMapView which automatically selects the first annotation after a second using an NSTimer. The problem is a lot of stuff can happen in that second, including the view being removed from screen or entirely deallocated. Unfortunately, calling `invalidate` on the NSTimer when the view disappears is not robust enough, because very occasionally the NSTimer will fire a split second before, leading to `message sent to deallocated instance`.
David Foster
ah i see, well it seems you've exhausted the other possibilities, and your way seems like a good solution to me.
Jesse Naugher