Search code examples
iosobjective-cselectornstimer

How to perform delayed selector safely iOS


In viewDidAppear I show a popup to users after 3 seconds. What if user navigates to another viewController after timer begins. The selected function will try to execute & show popup when superview is no longer on screen. App does not crash or throw any errors but I want to confirm this is safe. Should I set a BOOL and assert isCurrentView is YES, within selector method?

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self performSelector:@selector(showPopup) withObject:nil afterDelay:2.5];
}

Solution

  • in viewDidDisappear

    -(void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:(BOOL)animated];       
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showPopup) object:nil];
    }