NSTime create a timeInterval

倖福魔咒の 提交于 2020-01-14 06:43:42

问题


I have the following code in my application in the method updateLabel2:

timeLeft = [[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastDate"]];

[[self timer] setText:[NSString stringWithFormat:@"Time Remaining: %f", timeLeft]]; //Set the label text

Note that timer is a label.

and earlier, the following code is executed:

    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastDate"];


self.repeatTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                               target:self
                                             selector:@selector(updateLabel2) 
                                             userInfo:nil
                                              repeats:YES];

My problem is that timeLeft is being set to random integers which are definetly not what the timeIntervals should be, and are not within one second of each other either.


回答1:


Your format-string is wrong:
Because NSTimeInterval is a floating point type, you need to either

  • use the appropriate placeholder %f instead of %d or
  • cast timeLeft to an int while calling -[NSString stringWithFormat:].

Which — I think — is, what Justin referred to.

Aside

Considering what you're doing there:
Shouldn't that be "Time elapsed"?



来源:https://stackoverflow.com/questions/5006642/nstime-create-a-timeinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!