NSTimer with anonymous function / block?

Chris picture Chris · Feb 17, 2013 · Viewed 21.8k times · Source

I want to be able to schedule three small events in the future without having to write a function for each. How can I do this using NSTimer? I understand blocks facilitate anonymous functions but can they be used within NSTimer and if so, how?

[NSTimer scheduledTimerWithTimeInterval:gameInterval  
         target:self selector:@selector(/* I simply want to update a label here */) 
         userInfo:nil repeats:NO];

Answer

Reno Jones picture Reno Jones · Feb 17, 2013

You can make use of dispatch_after if you want to achieve something similar to NSTimer and block execution.

Here is the sample code for the same:

    int64_t delayInSeconds = gameInterval; // Your Game Interval as mentioned above by you

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

        // Update your label here. 

    });

Hope this helps.