问题
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