ios 如何保存我的 iPhone 应用程序的用户首选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3566140/
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
How do I save user preferences for my iPhone app?
提问by Toastor
The question title pretty much gives it away - I'd like my app to remember a few things. It's some sort of calculator, so it should save the last used values and some user selectable settings.
问题标题几乎暴露了它 - 我希望我的应用程序记住一些事情。它是某种计算器,因此它应该保存上次使用的值和一些用户可选择的设置。
Basically I'd like to save a handful of floats and BOOLs and load them again the next time the app loads.
基本上我想保存一些浮点数和 BOOL 并在下次加载应用程序时再次加载它们。
What's the best and easiest way to do that?
最好和最简单的方法是什么?
Thanks!!
谢谢!!
回答by Gauloises
One of the easiest ways would be saving it in the NSUserDefaults
:
最简单的方法之一是将其保存在NSUserDefaults
:
Setting:
环境:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:value
forKey:key];
// – setBool:forKey:
// – setFloat:forKey:
// in your case
[userDefaults synchronize];
Getting:
获得:
[[NSUserDefaults standardUserDefaults] objectForKey:key];
– boolForKey:
and
和
– floatForKey:
in your case.
– floatForKey:
在你的情况下。
回答by Chris
Besides the very good NSUserDefaults approach, there is another easy way to store data from an NSArray,NSDictionary or NSData in a file. You can use these methods as well:
除了非常好的 NSUserDefaults 方法之外,还有另一种简单的方法可以将来自 NSArray、NSDictionary 或 NSData 的数据存储在文件中。您可以使用这些方法,以及:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
respectively (for a NSDictionary):
分别(对于 NSDictionary):
+ (id)dictionaryWithContentsOfFile:(NSString *)path
you just have to give a valid path to a location. According to the iOS Application Programming Guide, the /Library/Caches directory would be the best place to store data that you need to persist between app launches. (see here)
你只需要提供一个有效的位置路径。根据 iOS 应用程序编程指南,/Library/Caches 目录将是存储应用程序启动之间需要保留的数据的最佳位置。(见这里)
In order to store/load a dictionary from a filed called "managers" in your document directoy you could use these methods:
为了从文档目录中名为“managers”的文件中存储/加载字典,您可以使用以下方法:
-(void) loadDictionary {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//create a destination file name to write the data :
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName];
if (panelLibraryContent != nil) {
// load was successful do something with the data...
} else {
// error while loading the file
}
}
-(void) storeDictionary:(NSDictionary*) dictionaryToStore {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the
//cache directory:
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
if (dictionaryToStore != nil) {
[dictionaryToStore writeToFile:fullFileName atomically:YES];
}
}
Anyway this approach is very limited and you have to spend a lot of extra work if you want to store more complex data. In that case the CoreData API is very very handy.
无论如何,这种方法非常有限,如果要存储更复杂的数据,则必须花费大量额外的工作。在这种情况下,CoreData API 非常方便。
回答by Suragch
In Swift:
在斯威夫特:
Setting
环境
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(value, forKey: key)
// userDefaults.setFloat(12.34, forKey: "myFloatKey")
// userDefaults.setBool(true, forKey: "myBoolKey")
Note that for iOS 8 and later, calling userDefaults.synchronize()
is not recommended.
需要注意的是为iOS 8及更高版本,通话userDefaults.synchronize()
是不推荐使用。
Getting
得到
let userDefaults = NSUserDefaults.standardUserDefaults()
if let value = userDefaults.objectForKey(key) {
print(value)
}
Note that userDefaults.boolForKey
and userDefaults.floatForKey
both return non optional values, so they would never be nil
(only false
or 0.0
).
请注意,userDefaults.boolForKey
anduserDefaults.floatForKey
都返回非可选值,因此它们永远不会nil
(仅false
或0.0
)。
Further reading
进一步阅读
回答by ennuikiller
You are looking for NSUserDefaults
您正在寻找 NSUserDefaults
回答by PJ_Finnegan
Swift 4 / Linux
斯威夫特 4 / Linux
Apparently something has changed. Now there's the UserDefault
class.
Check these links:
显然有些事情发生了变化。现在UserDefault
上课了。检查这些链接:
https://developer.apple.com/documentation/foundation/userdefaults
https://developer.apple.com/documentation/foundation/userdefaults
https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-userdefaults
https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-userdefaults