2

Is there anyway to write code instead of setting a selector to method to call in NSTimer? If i want to print hello world after 5 sec i can do it like this.

[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(helloWorld:) userInfo:nil repeats:NO];

and have this function

-(void)helloWorld:(NSTimer*)aTimer {
    NSLog(@"Hello World!");
}

But instead of writeing functions for every timer you have is it possible to add NSLog(@"Hello World!") in the same line as where i create the timer?

David
  • 1,298
  • 1
  • 14
  • 27
  • 1
    Duplicate of http://stackoverflow.com/questions/4007023/blocks-instead-of-performselectorwithobjectafterdelay where you might find a suitable answer. – hotpaw2 May 26 '11 at 00:15

2 Answers2

3

I use this code– an NSTimer category:

https://gist.github.com/250662/d4f99aa9bde841107622c5a239e0fc6fa37cb179

Peter DeWeese
  • 17,853
  • 8
  • 77
  • 100
2

Some methods allow you to pass a code block as a parameter. Unfortunately this isn't supported for NSTimer.

highlycaffeinated
  • 19,539
  • 7
  • 58
  • 91