如何将整数保存到NSUserDefaults?

时间:2022-10-17 07:35:54

Does anyone know how I would go about saving my high score integer to NSUserDefaults so I can load it later?

有谁知道如何将我的高分整数保存到NSUserDefaults所以我可以在以后加载它?

2 个解决方案

#1


57  

[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScore"];

… to get it back:

......把它拿回来:

NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];

This is explained very simply in the documentation.

这在文档中非常简单地解释。

#2


10  

More generally, you can save Foundation class objects to the user defaults, e.g.:

更一般地说,您可以将Foundation类对象保存为用户默认值,例如:

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"kHighScore"];

and

NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];

But the convenience method is there for taking in an NSInteger directly.

但是方便的方法是直接接收NSInteger。

I prefer to use the more agnostic -setObject: and -objectForKey: because it more cleanly separates the object type from access to the dictionary.

我更喜欢使用更不可知的-setObject:和-objectForKey:因为它更清晰地将对象类型与对字典的访问分开。

#1


57  

[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScore"];

… to get it back:

......把它拿回来:

NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];

This is explained very simply in the documentation.

这在文档中非常简单地解释。

#2


10  

More generally, you can save Foundation class objects to the user defaults, e.g.:

更一般地说,您可以将Foundation类对象保存为用户默认值,例如:

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"kHighScore"];

and

NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];

But the convenience method is there for taking in an NSInteger directly.

但是方便的方法是直接接收NSInteger。

I prefer to use the more agnostic -setObject: and -objectForKey: because it more cleanly separates the object type from access to the dictionary.

我更喜欢使用更不可知的-setObject:和-objectForKey:因为它更清晰地将对象类型与对字典的访问分开。