在iOS / iPhone上冻结正常运行时间

时间:2011-05-18 23:30:07

标签: iphone objective-c ios ipad

有人知道为什么我会通过以下方法体验奇怪的正常运行时间吗?

NSProcessInfo *processInfo = [NSProcessInfo processInfo];
NSTimeInterval systemUptime = [processInfo systemUptime];

第一分钟,一切看起来都不错,但是当我回到应用程序上几小时或几天后,正常运行时间仍然是相同的:30分钟,或1小时34分...它似乎随机冻结。主要在iPhone 4上(很少在模拟器或iPad上)

它可能与我展示它的方式有关:

+ (NSTimeInterval)uptime:(NSNumber **)days hours:(NSNumber **)hours mins:(NSNumber **)mins
{
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
        //START UPTIME///////
    NSTimeInterval systemUptime = [processInfo systemUptime];
        // Get the system calendar
    NSCalendar *sysCalendar = [NSCalendar currentCalendar];
        // Create the NSDates
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:(0-systemUptime)]; 
    unsigned int unitFlags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *c = [sysCalendar components:unitFlags fromDate:date toDate:[NSDate date]  options:0]; 
        //NSString *uptimeString = [NSString stringWithFormat:@"%dd %dh %dmin", [c day],[c hour],[c minute]];
    *days = [NSNumber numberWithInt:[c day]];
    *hours = [NSNumber numberWithInt:[c hour]];
    *mins = [NSNumber numberWithInt:[c minute]];
    [date release];
        //END UPTIME////////

    return systemUptime;
}

后来在代码中:

NSNumber *uptimeDays, *uptimeHours, *uptimeMins;
[CJGDevice uptime:&uptimeDays hours:&uptimeHours mins:&uptimeMins];
NSString *uptimeString = [NSString stringWithFormat:@"%@d %@h %@min",
                          [uptimeDays stringValue],
                          [uptimeHours stringValue],
                          [uptimeMins stringValue]];
编辑:在iPad和iPhone上录制结果3天后我可以看到正常运行时间错误,运行时间太慢,我们等待的时间越多,显然已经晚了

3 个答案:

答案 0 :(得分:9)

这种方法可以解决问题:

- (time_t)uptime
{
    struct timeval boottime;
    int mib[2] = {CTL_KERN, KERN_BOOTTIME};
    size_t size = sizeof(boottime);
    time_t now;
    time_t uptime = -1;

    (void)time(&now);    

    if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) 
    {
        uptime = now - boottime.tv_sec;
    }
    return uptime;
}

感谢Alastair Stuart的link

答案 1 :(得分:5)

该方法是系统自启动后唤醒的时间(不是实际时钟时间),iOS设备通常会花费大量时间睡眠。这就是为什么它没有像你期望的那样增加。

来源:http://developer.apple.com/library/ios/releasenotes/Cocoa/Foundation.html

答案 2 :(得分:2)

看看达尔文的正常运行命令如何做到这一点。 The source is here

您要阅读的部分是pr_header()函数,尤其是这些行:

if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) {
    uptime = now - boottime.tv_sec;