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)
这个片段有几点:
NSTimeInterval
而不是double
在第二行.它们是等价的,因为它只是一个typedef,但它使代码更清晰.[NSDate date]
并从中获取时间间隔groceryItem.lastPurchased
.这将返回一个groceryItem.lastPurchased
与过去一样长的正数.groceryItem.lastPurchased
直接传递给时间间隔计算.为仅使用一次的项声明变量并不总是一个好主意,尤其是在非垃圾收集环境中.尽管声明变量可能会使代码更具可读性,但还有其他方法可以提高可读性.例如,在这种情况下,更改属性groceryItem.lastPurchasedDate
使其更清晰.timeIntervalSinceNow将返回接收者与当前日期和时间之间的间隔.如果接收器早于当前日期和时间,则返回值为负.如果接收器晚于当前日期和时间,则返回值为正.
希望这可以帮助.
归档时间: |
|
查看次数: |
8241 次 |
最近记录: |