简体   繁体   中英

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 NSLog outputs.

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.

您是否尝试过在dealloc使其无效

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM