objective-c - NSTimer 不调用方法

标签 objective-c cocoa nstimer

我现在真的很沮丧,用谷歌搜索了整个互联网,偶然发现了 SO,但仍然没有找到解决方案。

我正在尝试实现一个 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];

相反。

关于objective-c - NSTimer 不调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6074337/

相关文章:

iphone - CoreMotion - 磁场始终为 0

ios - 使用 iOS 编码 mpeg-1 视频

objective-c - 将对象添加到数组时程序崩溃

objective-c - 将 NSNumbers 的 NSArray 转换为 NSStrings 数组的更好方法

iphone - NSTimer 没有停止?

iphone - Objective-C - 对 NSMutableStrings 使用 deleteCharactersInRange

ios - 使用 AFNetworking 进行图像缓存

objective-c - 可以在运行时添加.strings 资源文件吗?

swift - @selector() 在 Swift 中?

ios - 取消初始化/无效定时器