简体   繁体   中英

iPhone: NSTimer

Have a question... I have Timer

 [NSTimer scheduledTimerWithTimeInterval:120                                                              
target:self                                           
selector:@selector(action1:)                                                      
userInfo:nil                                                       
repeats:YES];

But when I move to another screen of my app I want to change selector...How can I change selector ? I know that I can stop my timer and set a new one, but I don't wont to reset a time remained to fire action...Thanks....

You can't. NSTimer takes its targeting information in its instantiation methods, and doesn't expose any properties to modify that later.

You're going to have to invalidate this timer and create a new one on the new target.

It looks like the selector is immutable. I would wrap this functionality into it's only tiny class with a setSelector method. Internally, create the NSTimer with a private selector. Inside that method, call the external selector that's been set using the setSelector method.

You might call a generic selector that, depending on the page shown, calls other methods:

    [NSTimer scheduledTimerWithTimeInterval:120                                                              
    target:self                                           
    selector:@selector(selectorDispatcher)                                                      
    userInfo:nil                                                       
    repeats:YES];

and than obviously your method selectorDispatcher will look something like:

    - (void) selectorDispatcher{

         if(pageshown1)
            [self callmethod1];
         else
            [self callmethod2];
    }

I think this should work...let me know!

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