Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer with anonymous function / block?

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]; 
like image 289
Chris Avatar asked Feb 17 '13 19:02

Chris


1 Answers

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.

like image 120
Reno Jones Avatar answered Oct 14 '22 15:10

Reno Jones