以下是NSTimer中的Objective-C类别,以进行基于块的NSTimers的触发.我看不到任何错误,但是我得到的是,我传递给schedule …方法的块正在被释放,尽管我打电话给它.
我失踪了什么
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
解决方法
我发现这个代码在http://orion98mc.blogspot.ca/2012/08/objective-c-blocks-for-fun.html
做得好
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }] selector:@selector(main) userInfo:nil repeats:NO ];