timeIntervalSinceNow返回随机数

Ben*_*Ben 3 iphone cocoa-touch objective-c

timeInterval不断返回随机数.我认为每次通话时间隔会继续增加,但有时我会得到负数,有时会得到正数.

NSDate *date = groceryItem.lastPurchased;
double timeInterval = [date timeIntervalSinceNow];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", timeInterval];
Run Code Online (Sandbox Code Playgroud)

wil*_*ood 11

%d用于整数,使用%f表示double

[NSString stringWithFormat:@"%f", timeInterval];
Run Code Online (Sandbox Code Playgroud)


Abi*_*ern 11

试试这个:

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:groceryItem.lastPurchased];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%f", timeInterval];
Run Code Online (Sandbox Code Playgroud)

这个片段有几点:

  1. 我用过NSTimeInterval而不是double在第二行.它们是等价的,因为它只是一个typedef,但它使代码更清晰.
  2. 我不是从过去的日期得到时间间隔,而是计算现在的日期和时间,[NSDate date]并从中获取时间间隔groceryItem.lastPurchased.这将返回一个groceryItem.lastPurchased与过去一样长的正数.
  3. 我编辑了我的原始代码,groceryItem.lastPurchased直接传递给时间间隔计算.为仅使用一次的项声明变量并不总是一个好主意,尤其是在非垃圾收集环境中.尽管声明变量可能会使代码更具可读性,但还有其他方法可以提高可读性.例如,在这种情况下,更改属性groceryItem.lastPurchasedDate使其更清晰.


Jes*_*her 7

如果接收器早于当前日期和时间,则返回值为负.所以,如果date是以前,现在这将是负面的.


Raf*_*ira 6

timeIntervalSinceNow将返回接收者与当前日期和时间之间的间隔.如果接收器早于当前日期和时间,则返回值为负.如果接收器晚于当前日期和时间,则返回值为正.

希望这可以帮助.