NSDate的dateWithTimeIntervalSinceNow中的否定NSTimeInterval:

Tyi*_*ilo 2 objective-c nsdate ios

来自iOS文档:

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.
Run Code Online (Sandbox Code Playgroud)

但是,此代码在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;
}
Run Code Online (Sandbox Code Playgroud)

它应该从近期生成半随机日期和时间.

Tyi*_*ilo 7

正如Hot Licks所说,这是由于在数字为负数而不是首先否定数字之后投射到NSTimeInterval然后施放它.

该行的固定版本如下所示:

NSDate* date = [NSDate dateWithTimeIntervalSinceNow:-(NSTimeInterval)((u_int32_t)i * 12 * 60 * 60 + arc4random_uniform(8 * 60 * 60))];
Run Code Online (Sandbox Code Playgroud)