Objective C equivalent to javascripts setTimeout?

后端 未结 4 1025
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 21:10

I was wondering whether there is a solution to raise an event once after 30 seconds or every 30 seconds in CocoaTouch ObjectiveC.

相关标签:
4条回答
  • 2020-12-30 21:50

    Take a look at the NSTimer class:

    NSTimer *timer;
    ...
    timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
    [timer fire];
    

    Somewhere else you have the actual method that handles the event:

    - (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
       NSLog(@"fired!");
    }
    
    0 讨论(0)
  • 2020-12-30 21:58
    +[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
    

    Documentation

    You may also want to look at the other NSTimer methods

    0 讨论(0)
  • 2020-12-30 21:59

    The performSelector: family has its limitations. Here is the closest setTimeout equivalent:

    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
    dispatch_after(delay, dispatch_get_main_queue(), ^(void){
        // do work in the UI thread here
    });
    

    EDIT: A couple of projects that provide syntactic sugar and the ability to cancel execution (clearTimeout):

    • https://github.com/Spaceman-Labs/Dispatch-Cancel
    • https://gist.github.com/zwaldowski/955123
    0 讨论(0)
  • 2020-12-30 22:02

    There are a number of options.

    The quickest to use is in NSObject:

    - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
    

    (There are a few others with slight variations.)

    If you want more control or to be able to say send this message every thirty seconds you probably need NSTimer.

    0 讨论(0)
提交回复
热议问题