ios 如何将整数保存到 NSUserDefaults?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1482097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:27:48  来源:igfitidea点击:

How do you save an integer to NSUserDefaults?

iphoneios

提问by iKenndac

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

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

回答by iKenndac

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

… to get it back:

… 取回它:

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

This is explained very simply in the documentation.

文档中对此进行了非常简单的解释。

回答by Alex Reynolds

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 NSIntegerdirectly.

但是有一个方便的方法是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:因为它更清晰地将对象类型与对字典的访问分开。