objective-c - 使用 fireDate 初始化的 NSTimer 不会触发

标签 objective-c cocoa nstimer

我正在尝试使用 NSTimer 来调用方法,但它不起作用。 我需要此方法在用户在日历上设置的特定日期和时间运行一次。

我的 viewDidLoad 方法中有这段代码:

NSDateComponents *comps = [[NSDateComponents alloc] init];

[comps setDay:24];
[comps setMonth:10];
[comps setYear:2011];

[comps setHour:23];
[comps setMinute:11];
[comps setSecond:0];


NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
schedulerTimer=[[NSTimer alloc] initWithFireDate:date interval:0 target:self selector:@selector(recordByScheduler:) userInfo:nil repeats:false];

但是这段代码什么也没做。可能我误解了 NSCalendar。我应该在这里做什么?第二个问题:应用程序在后台运行时 NSTimer 是否被触发?

最佳答案

你需要在runloop中调度定时器。

[[NSRunLoop currentRunLoop] addTimer:schedulerTimer forMode:NSDefaultRunLoopMode];

或类似,视情况而定。

对问题编辑的回复:

当您的应用程序处于后台时,不会触发 NSTimer。

关于objective-c - 使用 fireDate 初始化的 NSTimer 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7882500/

相关文章:

ios - 如何使用.xcdatamodel使用复合谓词创建获取请求模板

objective-c - 为什么这个 NSTask TerminationStatus 返回 nil 值?

objective-c - 拖放不适用于 NSBox 的子类

objective-c - 在 objective-c 中使用基于时间的 ProgressBar

ios - 定时器上的 Objective C 加载图标

objective-c - 资源路径 :ofType: returns 'nil' if a build rule for 'Data model version files' is used

iphone - Base64 编码图像在传输到服务器期间损坏

objective-c - 有没有办法使用 AppleScript 单击 osx 菜单项而不访问 "System Events"?

iphone - 如何在 iPhone/Mac 上使用 CoreAudio 合成声音

objective-c - 使用计时器检查 if 内的条件