2011-05-18 54 views
6

有人會通過以下方法知道我爲什麼會遇到奇怪的正常運行時間嗎?iOS/iPhone上的凍結正常運行時間

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

對於第一分鐘,似乎一切都很好,但是當我回來的應用數小時或數天laters的正常運行時間仍然是相同的:30分鐘,或1h34 ...這似乎在隨機時刻凍結。主要是在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]]; 

編輯:3後天在iPad和iPhone上記錄結果我可以看到,這個正常運行時間是錯誤的,時間運行得太慢,我們越等待越是顯而易見,它晚了

+0

** 32分鐘前**它顯示** 2d 12h 21min **在iPhone4上,現在顯示** 2d 12h 35min ** – chriscatfr 2011-05-19 00:37:23

回答

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; 
} 

感謝阿拉斯泰爾·斯圖爾特的link

5

該方法是時間量th e系統自啓動以來一直清醒(不是真實世界的時鐘時間),iOS設備通常會花費大量時間睡眠。這就是爲什麼它沒有像你期望的那樣增加。

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

+1

謝謝!在官方文檔中,它仍然說**「返回計算機重新啓動以來的時間。」**並在您的鏈接上說**「這將返回自上次重新啓動以來系統已清醒的時間「**。同時這成爲一個有用的「其他」數據。我看到應用商店上的iNet顯示正確的正常運行時間,我會保持希望 – chriscatfr 2011-05-21 15:28:44

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;