对积木知之甚少。你会如何去模仿一个重复NSTimer
with dispatch_after()
?我的问题是,当应用程序移至后台时,我想“暂停”一个计时器,但子类化NSTimer
似乎不起作用。
我尝试了一些似乎有效的方法。我无法判断它的性能影响或是否可以大大优化。欢迎任何意见。
#import "TimerWithPause.h"
@implementation TimerWithPause
@synthesize timeInterval;
@synthesize userInfo;
@synthesize invalid;
@synthesize invocation;
+ (TimerWithPause *)scheduledTimerWithTimeInterval:(NSTimeInterval)aTimeInterval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)aUserInfo repeats:(BOOL)aTimerRepeats {
TimerWithPause *timer = [[[TimerWithPause alloc] init] autorelease];
timer.timeInterval = aTimeInterval;
NSMethodSignature *signature = [[aTarget class] instanceMethodSignatureForSelector:aSelector];
NSInvocation *aInvocation = [NSInvocation invocationWithMethodSignature:signature];
[aInvocation setSelector:aSelector];
[aInvocation setTarget:aTarget];
[aInvocation setArgument:&timer atIndex:2];
timer.invocation = aInvocation;
timer.userInfo = aUserInfo;
if (!aTimerRepeats) {
timer.invalid = YES;
}
[timer fireAfterDelay];
return timer;
}
- (void)fireAfterDelay {
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, self.timeInterval * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(delay, queue, ^{
[invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];
if (!invalid) {
[self fireAfterDelay];
}
});
}
- (void)invalidate {
invalid = YES;
[invocation release];
invocation = nil;
[userInfo release];
userInfo = nil;
}
- (void)dealloc {
[self invalidate];
[super dealloc];
}
@end