iOS 等效于 Android 共享首选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19206762/
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
iOS Equivalent For Android Shared Preferences
提问by FaddishWorm
I am porting an Android app to iOS, one thing I used was the Shared Preferences in Android to save each time a level was complete.
我正在将 Android 应用程序移植到 iOS,我使用的一件事是 Android 中的共享首选项以在每次完成关卡时进行保存。
That way when the user gets back into the app, they can see they are up to level 3 or whatever.
这样当用户重新进入应用程序时,他们可以看到他们达到了 3 级或其他级别。
Is there a similar mechanism in iOS? or do I have to manually write out to an application specific file?
iOS中是否有类似的机制?或者我必须手动写出到特定于应用程序的文件?
If so, how do I write out to files only visible to my application?
如果是这样,我如何写出仅对我的应用程序可见的文件?
Thanks.
谢谢。
回答by SomeGuy
Use NSUserDefaults: - note that this is for small bits of data, such as the current level like you mentioned. Don't abuse this and use it as a large database, because it is loaded into memory every time you open your app, whether you need something from it or not (other parts of your app will also use this).
使用NSUserDefaults: -请注意,这是针对少量数据,例如您提到的当前级别。不要滥用它并将其用作大型数据库,因为每次打开应用程序时它都会加载到内存中,无论您是否需要从中获取某些内容(应用程序的其他部分也将使用它)。
Objective-C:
目标-C:
Reading:
读:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSString *currentLevelKey = @"currentlevel";
if ([preferences objectForKey:currentLevelKey] == nil)
{
// Doesn't exist.
}
else
{
// Get current level
const NSInteger currentLevel = [preferences integerForKey:currentLevelKey];
}
Writing:
写作:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSString *currentLevelKey = @"currentlevel";
const NSInteger currentLevel = ...;
[preferences setInteger:currentLevel forKey:currentLevelKey];
// Save to disk
const BOOL didSave = [preferences synchronize];
if (!didSave)
{
// Couldn't save (I've never seen this happen in real world testing)
}
.
.
Swift:
迅速:
Reading:
读:
let preferences = NSUserDefaults.standardUserDefaults()
let currentLevelKey = "currentLevel"
if preferences.objectForKey(currentLevelKey) == nil {
// Doesn't exist
} else {
let currentLevel = preferences.integerForKey(currentLevelKey)
}
Writing:
写作:
let preferences = NSUserDefaults.standardUserDefaults()
let currentLevelKey = "currentLevel"
let currentLevel = ...
preferences.setInteger(currentLevel, forKey: currentLevelKey)
// Save to disk
let didSave = preferences.synchronize()
if !didSave {
// Couldn't save (I've never seen this happen in real world testing)
}
回答by Ben
Here is an update for Swift 3
这是 Swift 3 的更新
Reading
读
let preferences = UserDefaults.standard
let currentLevelKey = "currentLevel"
if preferences.object(forKey: currentLevelKey) == nil {
// Doesn't exist
} else {
let currentLevel = preferences.integer(forKey: currentLevelKey)
}
Writing
写作
let preferences = UserDefaults.standard
let currentLevel = ...
let currentLevelKey = "currentLevel"
preferences.set(currentLevel, forKey: currentLevelKey)
Update
更新
From UserDefaults documentation
synchronize()
waits for any pending asynchronous updates to the defaults database and returns; this method is now unnecessary and shouldn't be used.
synchronize()
等待对默认数据库的任何挂起的异步更新并返回;这种方法现在是不必要的,不应该使用。
回答by Hasanaga
class Configuration {
static func value<T>(defaultValue: T, forKey key: String) -> T{
let preferences = UserDefaults.standard
return preferences.object(forKey: key) == nil ? defaultValue : preferences.object(forKey: key) as! T
}
static func value(value: Any, forKey key: String){
UserDefaults.standard.set(value, forKey: key)
}
}
Example
例子
//set
Configuration.value(value: "my_value", forKey: "key_1")
//get
let myValue = Configuration.value(defaultValue: "default_value", forKey: "key_1")
回答by Md Imran Choudhury
As per the previous answer, you already know that UserDefaults
is the equivalent to shared preferences in ios. You can create a common write function and for read create function based on data type. And call your required method from anywhere.
根据上一个答案,您已经知道这UserDefaults
相当于 ios 中的共享首选项。您可以根据数据类型创建一个通用的写入函数和读取创建函数。并从任何地方调用所需的方法。
ViewController.swift
视图控制器.swift
// write data
writeAnyData(key: "MY_KEY", value: "MyData")
// read string data
readStringData(key: "MY_KEY"), animated: true)
Utils.swift
实用工具.swift
// read and write user default
let userDefault = UserDefaults.standard
// write
func writeAnyData(key: String, value: Any){
userDefault.set(value, forKey: key)
userDefault.synchronize()
}
// read int values
func readIntData(key: String) -> Int{
if userDefault.object(forKey: key) == nil {
return 0
} else {
return userDefault.integer(forKey: key)
}
}
// read string values
func readStringData(key: String) -> String{
if userDefault.object(forKey: key) == nil {
return ""
} else {
return userDefault.string(forKey: key)!
}
}
// read bool value
func readBoolData(key: String) -> Bool{
if userDefault.object(forKey: key) == nil {
return false
} else {
return userDefault.bool(forKey: key)
}
}