[英]NSTimer doesn't call method
我現在真的很沮喪,谷歌搜索整個互聯網,偶然發現,仍然沒有找到解決方案。
我正在嘗試實現NSTimer,但我定義的方法不會被調用。 (正確設置秒數,使用斷點檢查)。 這是代碼:
- (void) setTimerForAlarm:(Alarm *)alarm {
NSTimeInterval seconds = [[alarm alarmDate] timeIntervalSinceNow];
theTimer = [NSTimer timerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
}
- (void) showAlarm:(Alarm *)alarm {
NSLog(@"Alarm: %@", [alarm alarmText]);
}
對象“theTimer”用@property定義:
@interface FooAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {
@private
NSTimer *theTimer;
}
@property (nonatomic, retain) NSTimer *theTimer;
- (void) setTimerForAlarm:(Alarm *)alarm;
- (void) showAlarm:(Alarm *)alarm;
我究竟做錯了什么?
timerWithTimeInterval只是創建一個計時器,但不會將它添加到任何運行循環中以便執行。 嘗試
self.theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
代替。
另外不要忘記檢查是否
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats
在主線程中調用。
您已經創建了一個NSTimer對象,但尚未安排它運行。 timerWithTimeInterval:target:selector:userInfo:repeats:創建一個計時器,您可以安排稍后運行,例如,在應用程序啟動時創建計時器,並在用戶按下按鈕時開始計時。 要么打電話
[[NSRunLoop currentRunLoop] addTimer:theTimer forMode:NSDefaultRunLoopMode]
在setTimerForAlarm結束或替換
theTimer = [NSTimer timerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
同
theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
它創建一個計時器並立即安排它。
那么你可能想在運行循環中實際安排你的NSTimer
:)而不是timerWithTimeInterval
使用scheduledTimerWithTimeInterval
。
theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
雖然所有答案都是正確的,但有一個更簡單的解決方案,根本不涉及NSTimer
。 您的setTimerForAlarm:
實現可以簡化為一個簡單的行:
[self performSelector:@selector(showAlarm:) withObject:alarm afterDelay:[[alarm alarmDate] timeIntervalSinceNow]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.