2012-04-24 85 views
2

From the iOS docs:負NSTimeInterval中的NSDate的dateWithTimeIntervalSinceNow:

seconds 
The number of seconds from the current date and time for the new date. Use a negative value to specify a date before the current date. 

但是這個代碼給出了2148日期:

#import <Foundation/Foundation.h> 
#import <stdlib.h> 

int main(int argc, const char * argv[]) 
{ 

    @autoreleasepool { 

     for(int i = 0; i < 30; i++) { 
      NSDate* date = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval)-((u_int32_t)i * 12 * 60 * 60 + arc4random_uniform(8 * 60 * 60))]; 
      NSLog(@"%@", date); 
     } 

    } 
    return 0; 
} 

它應該產生半隨機的日期和時間從過去不久。

+6

一個unsigned int類型的負爲正數。 – 2012-04-25 00:06:24

+0

@HotLicks感謝您在獲得否定之前將其轉換爲NSTimeInterval。 – Tyilo 2012-04-25 00:08:38

回答

7

正如Hot Licks所說,這是由於在將數字設爲負值而不是首先否定數字並將其轉換後轉換爲NSTimeInterval。

行的固定版本是這樣的:

NSDate* date = [NSDate dateWithTimeIntervalSinceNow:-(NSTimeInterval)((u_int32_t)i * 12 * 60 * 60 + arc4random_uniform(8 * 60 * 60))]; 
+0

謝謝,這工作完美! – jungledev 2015-08-13 19:55:48

相關問題