ブロックについてたくさん知りません。あなたはどのようにしてNSTimer
をdispatch_after()
と偽装しようとしますか?私の問題は、アプリがバックグラウンドに移動するときにタイマーを「一時停止」したいが、サブクラス化するNSTimer
は機能していないようだ。iPhone:NSTimerを模倣するためにdispatch_afterを使用する
私はうまくいくものを試しました。私はそのパフォーマンスへの影響や、それが大幅に最適化できるかどうかは判断できません。どんな入力も歓迎です。
#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
私はのUserInfo内の情報を格納することであることを試してみました。しかし、私はあなたがそれを更新できるとは思わない。タイマーオブジェクトの外にそれを格納することはあまり意味がありません。私は別のオブジェクトにタイマーをラップすることができますが、私はそれが非常にエレガントな解決策ではないと思います。まだそれを行うかもしれません... –
タイマー自体の中でその情報を保持したいのであれば、タイマーの 'userInfo'として可変コレクションを使用してみませんか?残りの時間をNSNumberの次の 'fireDate'までラップして、それをタイマーのuserInfoであるコレクションに格納します。 – danyowdee
私は実際にこれを行うカテゴリを作成しました:https://github.com/adamjernst/NSTimer- AbsoluteFireDate –