我的代码看起来像这样:
NSDate *currDate;
if(someCondition) {
currDate = [NSDate date];
}
//do some work
//calculate num of milli seconds passed since currDate was updated
if([currDate timeIntervalSinceNow] > MAX_MILLI_SECS) {
//do something
}
所以我有两个问题
- 由于 currDate 发生在我们计算 timeIntervalSinceNow 之前,返回的值是否为负数?
- 因为有一个代码路径,其中
currDate
从未初始化,如果我调用timeIntervalSinceNow
会发生什么没有经过if(someCondition)
阻止?
最佳答案
来自docs for -timeIntervalSinceNow
:
If the date object is earlier than the current date and time, this property’s value is negative.
如果代码是在启用 ARC 的情况下构建的,则 currDate
保证被初始化为 nil
。如果将其设置为其他内容的分支未被采用,则在调用 [currDate timeIntervalSinceNow]
时它仍然是 nil
。 nil
的消息返回消息类型的适当零值。因此,[currDate timeIntervalSinceNow]
的计算结果为 0。
如果代码不是在启用 ARC 的情况下构建的,那么 currDate
将是未初始化的垃圾并且结果是未定义的。
关于ios - timeIntervalSinceNow 用于获取耗时值的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451289/