【问题标题】:NSTimer initialized with fireDate does not fire用 fireDate 初始化的 NSTimer 不会触发
【发布时间】:2011-10-24 21:58:21
【问题描述】:

我正在尝试使用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 会被触发吗?

【问题讨论】:

    标签: objective-c cocoa nstimer


    【解决方案1】:

    您需要在运行循环中安排计时器。

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

    或类似,视情况而定。

    对问题编辑的回应:

    当您的应用程序在后台时,不会触发任何 NSTimer。

    【讨论】:

      【解决方案2】:

      如果您的应用在后台暂停,NSTimer 将不会触发。您可以根据需要使用 UILocalNotification。

      【讨论】:

      • 不错。我从来没有想过他可能一直在尝试设置警报,而实际上根本不想要一个 NSTimer。
      【解决方案3】:

      我尝试了@NJones 的答案,但没有奏效。经过一番折腾,我发现你应该在mainRunLoop 上使用NSRunLoopCommonModes,而不是NSDefaultRunLoopMode。例如,

      [[NSRunLoop mainRunLoop] addTimer:schedulerTimer forMode:NSRunLoopCommonModes];
      

      或者我现在使用的 Swift:

      NSRunLoop.mainRunLoop().addTimer(schedulerTimer, forMode: NSRunLoopCommonModes)
      

      不过,在我的情况下,阻止它工作的是模式,而不是运行循环。

      文件说:

      NSDefaultRunLoopMode

      处理 NSConnection 对象以外的输入源的模式。

      这是最常用的运行循环模式。

      适用于 iOS 2.0 及更高版本。

      NSRunLoopCommonModes

      使用该值作为模式添加到运行循环的对象被所有已声明为“通用”模式集合成员的运行循环模式监视;有关详细信息,请参阅 CFRunLoopAddCommonMode 的描述。

      适用于 iOS 2.0 及更高版本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-29
        • 2014-09-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多