Fogmeister Fogmeister - 15 days ago 4x
Objective-C Question

Invalidate a timer that belongs to a UIView subclass

I have a repeating timer that belongs to a UIView subclass.

The class has a nib that loads it and I'm using ARC.

I'd like to invalidate the timer when the UIView is either...

  1. Removed from its superview

  2. The ViewController that contains its superView is popped off the stack.

I can't seem to find a method like viewDidDisappear on UIView.

Is there any other way to intercept this?

At the moment, after the ViewController is popped the timer keeps firing and creating


For the view controller being popped: just use viewDidDisappear or similar. There's also UINavigationControllerDelegate that may be useful.

For the view itself: have you tried using willMoveToSuperview: method in UIView? I haven't verified this, but in theory the view will move to superview nil when it is removed from its superview.

So try the following in your view:

- (void)willMoveToSuperview:(UIView *)superview {
    if (!superview) {
        // cancel timers

There's also a willRemoveSubview: method, but that would get called on the superview rather than the view being removed.