Skip to content

Instantly share code, notes, and snippets.

@BenedictC
Created April 16, 2012 11:03
Show Gist options
  • Save BenedictC/2397777 to your computer and use it in GitHub Desktop.
Save BenedictC/2397777 to your computer and use it in GitHub Desktop.
NSTimer+Block category. Schedule a timer and use a block as the callback.
@interface NSTimer (EMKTimerBlocks)
+(id)EMK_scheduleTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)(NSTimer *))block;
@end
@implementation NSTimer (EMKTimerBlocks)
+(id)EMK_scheduleTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)(NSTimer *))block
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[block copy] forKey:@"block"];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(EMK_executeTimerBlock:) userInfo:userInfo repeats:repeats];
return timer;
}
+(void)EMK_executeTimerBlock:(NSTimer *)theTimer
{
void (^block)(NSTimer *) = [[theTimer userInfo] objectForKey:@"block"];
block(theTimer);
}
@end
@stuckj
Copy link

stuckj commented Aug 30, 2013

Shouldn't [block copy] be [[block copy] autorelease](or release after adding to dictionary)? Seems like you'd leak the reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment