Search code examples
iosobjective-cuialertviewalertnstimer

NSTimer fire specific code, not selector


I am trying to make a UIAlertView auto-dismiss after three seconds. I know how to make an NSTimer, and how to dismiss the UIAlertView separately, but I can't figure out how to make the dismiss-alert code run directly from the NSTimer, and NOT from a method.

Here is my code (the UIAlertView is named alert):

The timer:

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(method) userInfo:nil repeats:NO];

Dismiss the UIAlertView:

[alert dismissWithClickedButtonIndex:-1 animated:YES];

I can't dismiss the UIAlertView from a different method than the one that creates it (unless anyone knows of a way to that), so I need the above code to be called from within the first method, when the NSTimer fires.

Thanks in advance for any help / advice.


Solution

  • NSTimer only works with a selector, there is no way to directly call a method.

    Use dispatch_after instead of a timer.

    UIAlertView *alert = ... // create the alert view
    [alert show];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissWithClickedButtonIndex:alert.cancelButtonIndex animated:YES];
    });
    

    If you really want to use a timer you can do:

    UIAlertView *alert = ... // create the alert view
    [alert show];
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(dismissAlert:) userInfo:alert repeats:NO];
    

    Then your timer method would be:

    - (void)dismissAlert:(NSTimer *)timer {
        UIAlertView *alert = timer.userInfo;
    
        [alert dismissWithClickedButtonIndex:alert.cancelButtonIndex animated:YES];
    }