tam*_*gal 9 cocoa objective-c nstimer
我现在真的很沮丧,谷歌搜索整个互联网,偶然发现,仍然没有找到解决方案.
我正在尝试实现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]);
}
Run Code Online (Sandbox Code Playgroud)
对象"theTimer"用@property定义:
@interface FooAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {
@private
NSTimer *theTimer;
}
@property (nonatomic, retain) NSTimer *theTimer;
- (void) setTimerForAlarm:(Alarm *)alarm;
- (void) showAlarm:(Alarm *)alarm;
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Jim*_*eau 27
timerWithTimeInterval只是创建一个计时器,但不会将它添加到任何运行循环中以便执行.尝试
self.theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
Run Code Online (Sandbox Code Playgroud)
代替.
另外不要忘记检查是否
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats
Run Code Online (Sandbox Code Playgroud)
在主线程中调用.
小智 7
您已经创建了一个NSTimer对象,但尚未安排它运行.timerWithTimeInterval:target:selector:userInfo:repeats:创建一个计时器,您可以安排稍后运行,例如,在应用程序启动时创建计时器,并在用户按下按钮时开始计时.要么打电话
[[NSRunLoop currentRunLoop] addTimer:theTimer forMode:NSDefaultRunLoopMode]
Run Code Online (Sandbox Code Playgroud)
在setTimerForAlarm结束或替换
theTimer = [NSTimer timerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
Run Code Online (Sandbox Code Playgroud)
同
theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(showAlarm:)
userInfo:alarm repeats:NO];
Run Code Online (Sandbox Code Playgroud)
它创建一个计时器并立即安排它.
| 归档时间: |
|
| 查看次数: |
6462 次 |
| 最近记录: |