NSUserDefaults with time floats

99封情书 提交于 2019-12-25 02:58:14

问题


I'm making a game in which the user must complete a task as quickly as possible, and I would like to display the user's best time and update the best time when he or she achieves a new one. I have:

float BestTimeValue
float starttime
-(void)start{
starttime += 0.001;
timelabel.text = [NSString stringWithFormat:@"%.3f", starttime];
}
if (starttime < BestTimeValue) {
    [[NSUserDefaults standardUserDefaults] setObject:starttime forKey:[@"BestTimeValue"];
}

and in my viewdidload:

BestTimeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"BestTimeSaved"];

starttime stops when the game is over, but the value won't display in the label. Thanks!


回答1:


You can't use a float with the setObject:forKey: and objectForKey: methods.

Use setFloat:forKey: and floatForKey:.

if (starttime < BestTimeValue) {
    [[NSUserDefaults standardUserDefaults] setFloat:starttime forKey:[@"BestTimeValue"];
}


BestTimeValue = [[NSUserDefaults standardUserDefaults] floatForKey:@"BestTimeSaved"];



回答2:


[[NSUserDefaults standardUserDefaults] setObject: forKey:] As the name says, it only accept object like NSString, NSNumber, NSDictionary, etc.

So you have to use other method [[NSUserDefaults standardUserDefaults] setFloat: forKey] or save the float in a NSNumber to use the setObjet Method [NSNumber numberWithFloat:thefloat];



来源:https://stackoverflow.com/questions/24591241/nsuserdefaults-with-time-floats

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