【问题标题】:Timer is not upadating when app come Foreground to Background当应用程序从前台到后台时计时器不更新
【发布时间】:2012-01-09 13:35:04
【问题描述】:

我尝试运行倒数计时器应用。

当我从后台到前台时,每次我的计时器开始落后 1 秒,

我得到了应用程序在后台运行时的系统时间,并得到了应用程序进入前台的时间与这段代码之间的差异,

        NSDate *oldDate = [dateFor dateFromString:oldD];
        NSLog(@"Old Date in Timer : %@",oldDate);

        NSDate *newcurrentdate = [NSDate date];
        NSLog(@"NEWCURRENTDATE:%@",newcurrentdate);

        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *componentsss = [gregorianCalendar components:unitFlags
                                                              fromDate:oldDate
                                                                toDate:newcurrentdate
                                                               options:0];
        [gregorianCalendar release];

有了这个,我得到了差异。当应用程序从后台到前台时的特定秒,

将此秒添加到我的计时器代码中以更新计时器,

     ticks =ticks + 1;    
        if(ticks > 59)
        {
            minute = minute + 1;
            ticks = 0;
            if(minute > 59)
            {
                hour = hour + 1;
                minute = 0;
                if(hour > 23)
                {
                    hour = 0;
                }
            }
        }

当第一次开始时它运行良好,但是当从后台到前台时,它的计时器每次都落后一秒,

我尝试在我的代码中添加 1 秒,但它没有给出特定的计时器值,

我该怎么做?

【问题讨论】:

  • 您是如何收到“ticks”的?你在使用 NSTimer 吗?

标签: iphone objective-c cocoa-touch ios4 timer


【解决方案1】:

使用 timeIntervalSinceNow 或 timeIntervalSinceDate 来获取当前时间和开始日期之间的差异,而不是通过增加变量来计算滴答声会更容易吗?

要即时获取此间隔的分钟和小时,您可以执行以下操作:

minute = ((int) (ticks / 60)) % 60;
hour = ((int) (ticks / 3600)) % 24;

这应该会给出更准确的时间安排。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多