开发者

How can I trigger a method every 10 seconds without using NSTimer?

I would like to call a method every 10 seconds, but I want to use something other than NSTimer. What could I use to do this?开发者_JS百科


I know you said you didn't want to use timers, but just to make sure you know how simple it would be with a timer...

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


If you dont want to use the timer, you can use GCD which internally will make use of NSOperationQueue, nevertheless will work in all cases. For eg: i had a class which was inherited from NSOperation so the above methods didn't work so i had go go with GCD:

    double delayInSeconds = 3.0;      
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_after(popTime, queue, ^{
        [self methodYouWantToCall];  
    });

The above code calls the method methodYouWantToCall after every three seconds.


You can create a loop with performSelector:withObject:afterDelay: setting afterDelay to 10.0.

I don't recommend this though, use an NSTimer.

- (void)callMeEvery10Seconds
{
    [self performSelector:@selector(callMeEvery10Seconds) 
               withObject:nil 
               afterDelay:10.0];

    // ... code comes here ...
}


If you are not using Cocos2D, you have to use a NSTimer to do this....

If you are using Cocos2D, use the schedule method

here's a link below that shows both :

How can I create a count down timer for cocos2d?


The easiest way to do so is:

- (void)scheduleLoopInSeconds:(NSTimeInterval)delayInSeconds
{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_after(popTime, queue, ^{
        [self callWhatEverMethodYouWant];
        [self shceduleLoopcaInSeconds:delayInSeconds];//set next iteration
    });

}

// now whenever you like call this, and it will be triggering  "callWhatEverMethodYouWant" every 10 secs.
[self shceduleLoopcaInSeconds:10.0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜