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
I found this code over at http://orion98mc.blogspot.ca/2012/08/objective-c-blocks-for-fun.html
Great work
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7
target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }]
selector:@selector(main)
userInfo:nil
repeats:NO
];
You have a project on github that does the job !
Cocoapod BlocksKit, allow you to Blockify a bunch of Classes...
#import "NSTimer+BlocksKit.h"
[NSTimer bk_scheduledTimerWithTimeInterval:1.0 block:^(NSTimer *time) {
// your code
} repeats:YES];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With