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

chr*_*tfr 6 iphone objective-c ipad ios

有人会知道为什么我用以下方法经历了奇怪的正常运行时间吗?

NSProcessInfo *processInfo = [NSProcessInfo processInfo];
NSTimeInterval systemUptime = [processInfo systemUptime];
Run Code Online (Sandbox Code Playgroud)

第一分钟,一切看起来都很好,但是当我回到应用程序上几小时或几天后,正常运行时间仍然是相同的: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;
}
Run Code Online (Sandbox Code Playgroud)

后来在代码中:

NSNumber *uptimeDays, *uptimeHours, *uptimeMins;
[CJGDevice uptime:&uptimeDays hours:&uptimeHours mins:&uptimeMins];
NSString *uptimeString = [NSString stringWithFormat:@"%@d %@h %@min",
                          [uptimeDays stringValue],
                          [uptimeHours stringValue],
                          [uptimeMins stringValue]];
Run Code Online (Sandbox Code Playgroud)

编辑:在iPad和iPhone上记录结果3天后我可以看到这个正常运行时间错误,运行时间太慢,我们等待的时间越多,显然已经晚了

Mar*_*man 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;
}
Run Code Online (Sandbox Code Playgroud)

感谢Alastair Stuart的链接.


And*_*ico 5

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

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