The following is my Objective-C category on NSTimer to do block-based firing of NSTimers. I can't see anything wrong with it, but what I am getting is that the block I pass into the schedule...
method is being deallocated despite me calling copy
on it.
What am I missing?
typedef void(^NSTimerFiredBlock)(NSTimer *timer);
@implementation NSTimer (MyExtension)
+ (void)timerFired:(NSTimer *)timer
{
NSTimerFiredBlock blk = timer.userInfo;
if (blk != nil) {
blk(timer);
}
}
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
repeats:(BOOL)repeats
callback:(NSTimerFiredBlock)blk
{
return [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(timerFired:)
userInfo:[blk copy]
repeats:repeats];
}
@end
(void)timerFired:(NSTimer *)timer
should be an instance method-
, not a class method+
. The same probably applies toscheduledTimerWithTimeInterval
, but I am less sure about that. – Erythrocytometerself
as the target strongly suggests an instance method. All code samples ofNSTimer
that I've seen use instance methods for selectors as well. – Erythrocytometerdealloc
) foruserInfo
, does yourdealloc
gets called? – Erythrocytometer[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES callback:^(NSTimer* t){ NSLog(@"I'm here"); }];
call in myapplication:didFinishLaunchingWithOptions:
, and I am getting theI'm here
logs every second. – Erythrocytometer