1

When creating a timer, there are only these options:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds invocation:(NSInvocation *)invocation repeats:(BOOL)repeats;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats;

As you can see, there is no factory method that creates a timer with a block as its performing action.

Why is this? or am I missing something?

67cherries
  • 6,931
  • 7
  • 35
  • 51
Lay González
  • 2,901
  • 21
  • 41

2 Answers2

4

NSTimer precedes blocks and has not been updated to use them. If you want to use a block (rightly so), use a GCD dispatch source, i.e. dispatch_source_set_timer and related functions.

Under ARC, beware of retain cycles (though you would have had to beware of those with NSTimer too).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Blocks vs. target-selector/NSInvocation is a separate issue from NSTimer vs dispatch source timers. NSTimer works with run loops, whereas dispatch sources work on dispatch queues. You may need to use an NSTimer because you are working on a thread with run loop, and not on a dispatch queue. This has nothing to do with whether the action is specified with a block or not. – newacct May 22 '14 at 23:16
3

If you really want to you can pass in a block for the selector by creating a category. See this question. You can also use this github project to do this.

Community
  • 1
  • 1
67cherries
  • 6,931
  • 7
  • 35
  • 51