【问题标题】:Negative NSTimeInterval in NSDate's dateWithTimeIntervalSinceNow:NSDate 的 dateWithTimeIntervalSinceNow 中的负 NSTimeInterval:
【发布时间】:2012-04-24 23:59:12
【问题描述】:

From the iOS docs:

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

它应该从最近的过去生成半随机的日期和时间。

【问题讨论】:

  • 无符号整数的负数是正数。
  • @HotLicks 感谢您在修复负面之前转换为 NSTimeInterval。

标签: objective-c ios nsdate


【解决方案1】:

正如 Hot Licks 所说,这是由于在将数字设为负数后强制转换为 NSTimeInterval,而不是先否定数字然后再强制转换。

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

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

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 2011-12-19
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多