两个[NSDate date]之后的每一个都会返回不同的时间? [英] Will two [NSDate date] following each-other always return different times?

查看:74
本文介绍了两个[NSDate date]之后的每一个都会返回不同的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日期A和dateB总是不同吗?

  //两个[NSDate日期]彼此相邻
NSDate * dateA = [NSDate date]; // Line X
NSDate * dateB = [NSDate date]; // Line X + 1

就是这样,以下行总是返回NO?

  [dateA isEqualToDate:dateB] 

(始终)意味着像一个非常快的处理器不会如此快速地执行这两个命令,那么dateA和dateB将被分配相同的时间,具有次秒精度)。



我想为一些内部标识(不是DB相关)拥有一个唯一时间戳。

解决方案

没有承诺 dateB 将在 dateA 之后。 NSDate 基于系统时钟,可以根据NTP信息向前或向后发送。有两个 NSDate 次碰撞是非常令人惊讶的,但没有任何承诺不会发生。



如果你需要一些更好的东西,我会推荐 mach_absolute_time() CACurrentMediaTime()。它们在程序运行期间总是增加。它们是自上次启动设备以来的时间,因此它们在下次重新启动之前是唯一的。如果你需要一些总是增加的东西,那么通过跟踪偏移来构建它很容易。 mach_absolute_time()跟踪CPU刻度,所以我不相信在同一个线程上的两个调用可以返回相同的值。


Will dateA and dateB always be different?

// Two [NSDate date] following each other
NSDate *dateA = [NSDate date];    // Line X
NSDate *dateB = [NSDate date];    // Line X+1

That is, will the line below always return NO?

[dateA isEqualToDate:dateB]

("Always" meaning that like a very fast processor wouldn't execute the two commands so fast that dateA and dateB would be assigned the same time with "sub-second" accuracy).

I want to have a "unique" timestamp for some internal identification (not DB-related).

解决方案

There is no promise that dateB will be after dateA. NSDate is based on the system clock, which can bump forward or backward based on NTP information. It would be pretty surprising to have two NSDate times collide, but there's no promise it won't happen.

If you need something a little better, I'd recommend mach_absolute_time() or CACurrentMediaTime(). They always increase during the run of your program. They're measure time since the last boot of the device, so they're only unique until the next reboot. If you need something that always increases, it's pretty easy to build that by keeping track of an offset. mach_absolute_time() tracks CPU ticks, so I don't believe two calls to it on the same thread can return the same value.

这篇关于两个[NSDate date]之后的每一个都会返回不同的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆