iOS / iPhone 上的冻结时间无法持续运行

6
有人知道为什么我使用以下方法时会遇到奇怪的正常运行时间吗?
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天后,我发现这个正常运行时间是错误的,时间运行得太慢了,我们等待的时间越长,就越明显它是迟到了。


32分钟前,iPhone4 上显示为 2天12小时21分钟,现在显示为 2天12小时35分钟。 - chriscatfr
3个回答

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提供链接

在iOS 14中,从sysctl获取的值不同。即使设备没有重新启动。差异大约为30秒(最大值)。 - Manish Punia

5

1
谢谢!在官方文档中仍然说“返回计算机自上次重新启动以来的时间”,而在您提供的链接中,他们说“这返回系统自上次重新启动以来已经运行的时间”。与此同时,这成为了一个有用的“其他”数据。我看到应用商店上有iNet可以显示正确的正常运行时间,我会继续寻找希望。 - chriscatfr

2
看看达尔文的 uptime 命令是如何做到的。源代码在这里
你想要阅读的部分是 pr_header() 函数,特别是这些行附近:
if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) {
    uptime = now - boottime.tv_sec;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接