问题
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).
回答1:
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.
回答2:
There is no guarantee that they could be the same, although they could be depends on timing. The docs state that is returned the current time. It could change between the execution of those 2 lines, or it could stay the same if it happens fast enough.
http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/doc/uid/20000188-date
If you need uniques, then you should look at generating a GUID. Checkout this:
http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFUUIDRef/Reference/reference.html
回答3:
Technically speaking, yes. The calls to NSDate happen sequentially, not at the same time, so there will be some difference in time between the calls. But if you're looking for unique timestamps, then that's ok.
回答4:
NSDate has sub-millisecond accuracy, so it is hard to imagine a scenario where you would end up with identical timestamps. Faster future hardware would be expected to also provide timing accuracy that scales with the performance improvements.
Easy sample code—just get a series of NSDates without any intervening code. I bet they vary well above the final decimal place, which will indicate you will be just fine.
来源:https://stackoverflow.com/questions/7854932/will-two-nsdate-date-following-each-other-always-return-different-times