How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?
如何使用UserDefaults以Swift保存/检索字符串、布尔值和其他数据?
6 个解决方案
#1
171
ref: NSUserdefault objectTypes
裁判:nsuserdefaults objecttype
Swift 3 and above
Store
商店
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
检索
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
Remove
删除
UserDefaults.standard.removeObject(forKey: "Key")
Swift 2 and below
Store
商店
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()
Retrieve
检索
var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]
Remove
删除
NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")
UserDefaults suit name
another one property suit name, mostly its used for App Groups concept, the example scenario I taken from here :
另一个属性名称,主要用于应用程序组概念,我从这里取的示例场景:
The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.
用例是,我想将我的UserDefaults(不同的业务逻辑可能需要将UserDefaults分开分组)与一个标识符分开,就像Android的SharedPreferences一样。例如,当我的应用程序中的用户单击logout按钮时,我希望清除他的账户相关默认值,而不是设备的位置。
let user = UserDefaults(suiteName:"User")
use of userDefaults synchronize, the detail info has added in the duplicate answer.
使用userDefaults同步,详细信息已经添加到重复的答案中。
#2
6
Best way to use UserDefaults
使用UserDefaults的最好方法
Steps
步骤
- Create extension of UserDefaults
- 创建扩展UserDefaults
- Create enum with required Keys to store in local
- 创建枚举,并在本地存储所需的密钥
- Store and retrieve the local data wherever you want
- 在任何需要的地方存储和检索本地数据。
Sample
样本
extension UserDefaults{
//MARK: Check Login
func setLoggedIn(value: Bool) {
set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)
//synchronize()
}
func isLoggedIn()-> Bool {
return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)
}
//MARK: Save User Data
func setUserID(value: Int){
set(value, forKey: UserDefaultsKeys.userID.rawValue)
//synchronize()
}
//MARK: Retrieve User Data
func getUserID() -> Int{
return integer(forKey: UserDefaultsKeys.userID.rawValue)
}
}
enum for Keys used to store data
用于存储数据的键的enum
enum UserDefaultsKeys : String {
case isLoggedIn
case userID
}
Save in UserDefaults where you want
在用户默认设置中保存
UserDefaults.standard.setLoggedIn(value: true) // Bool
UserDefaults.standard.setUserID(value: result.User.id!) // integer
Retrieve data anywhere in app
在应用程序的任何地方检索数据
print("ID : \(UserDefaults.standard.getUserID())")
UserDefaults.standard.getUserID()
Remove Values
删除值
UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID)
This way you can store primitive data in best
通过这种方式,您可以最好地存储原始数据
Update You need no use synchronize() to store the values. As @Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail
不需要使用synchronize()来存储值。正如@Moritz指出的那样,这是不必要的,并给出了相关的文章。检查注释以获得更详细的信息。
#3
5
Swift 4 :
斯威夫特4:
Store
商店
UserDefaults.standard.set(object/value, forKey: "key_name")
Retrive
索取
var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]
Remove
删除
UserDefaults.standard.removeObject(forKey:"key_name")
#4
2
You can use NSUserDefaults
in swift this way,
可以使用NSUserDefaults这种方式,
@IBAction func writeButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("defaultvalue", forKey: "userNameKey")
}
@IBAction func readButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
let name = defaults.stringForKey("userNameKey")
println(name) //Prints defaultvalue in console
}
#5
1
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
#6
1
I saved NSDictionary normally and able to get it correctly.
我正常地保存了NSDictionary并且能够正确地获取它。
dictForaddress = placemark.addressDictionary! as NSDictionary
let userDefaults = UserDefaults.standard
userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)
// For getting data from NSDictionary.
//用于从NSDictionary获取数据。
let userDefaults = UserDefaults.standard
let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary
#1
171
ref: NSUserdefault objectTypes
裁判:nsuserdefaults objecttype
Swift 3 and above
Store
商店
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
检索
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
Remove
删除
UserDefaults.standard.removeObject(forKey: "Key")
Swift 2 and below
Store
商店
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()
Retrieve
检索
var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]
Remove
删除
NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")
UserDefaults suit name
another one property suit name, mostly its used for App Groups concept, the example scenario I taken from here :
另一个属性名称,主要用于应用程序组概念,我从这里取的示例场景:
The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.
用例是,我想将我的UserDefaults(不同的业务逻辑可能需要将UserDefaults分开分组)与一个标识符分开,就像Android的SharedPreferences一样。例如,当我的应用程序中的用户单击logout按钮时,我希望清除他的账户相关默认值,而不是设备的位置。
let user = UserDefaults(suiteName:"User")
use of userDefaults synchronize, the detail info has added in the duplicate answer.
使用userDefaults同步,详细信息已经添加到重复的答案中。
#2
6
Best way to use UserDefaults
使用UserDefaults的最好方法
Steps
步骤
- Create extension of UserDefaults
- 创建扩展UserDefaults
- Create enum with required Keys to store in local
- 创建枚举,并在本地存储所需的密钥
- Store and retrieve the local data wherever you want
- 在任何需要的地方存储和检索本地数据。
Sample
样本
extension UserDefaults{
//MARK: Check Login
func setLoggedIn(value: Bool) {
set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)
//synchronize()
}
func isLoggedIn()-> Bool {
return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)
}
//MARK: Save User Data
func setUserID(value: Int){
set(value, forKey: UserDefaultsKeys.userID.rawValue)
//synchronize()
}
//MARK: Retrieve User Data
func getUserID() -> Int{
return integer(forKey: UserDefaultsKeys.userID.rawValue)
}
}
enum for Keys used to store data
用于存储数据的键的enum
enum UserDefaultsKeys : String {
case isLoggedIn
case userID
}
Save in UserDefaults where you want
在用户默认设置中保存
UserDefaults.standard.setLoggedIn(value: true) // Bool
UserDefaults.standard.setUserID(value: result.User.id!) // integer
Retrieve data anywhere in app
在应用程序的任何地方检索数据
print("ID : \(UserDefaults.standard.getUserID())")
UserDefaults.standard.getUserID()
Remove Values
删除值
UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID)
This way you can store primitive data in best
通过这种方式,您可以最好地存储原始数据
Update You need no use synchronize() to store the values. As @Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail
不需要使用synchronize()来存储值。正如@Moritz指出的那样,这是不必要的,并给出了相关的文章。检查注释以获得更详细的信息。
#3
5
Swift 4 :
斯威夫特4:
Store
商店
UserDefaults.standard.set(object/value, forKey: "key_name")
Retrive
索取
var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]
Remove
删除
UserDefaults.standard.removeObject(forKey:"key_name")
#4
2
You can use NSUserDefaults
in swift this way,
可以使用NSUserDefaults这种方式,
@IBAction func writeButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("defaultvalue", forKey: "userNameKey")
}
@IBAction func readButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
let name = defaults.stringForKey("userNameKey")
println(name) //Prints defaultvalue in console
}
#5
1
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
#6
1
I saved NSDictionary normally and able to get it correctly.
我正常地保存了NSDictionary并且能够正确地获取它。
dictForaddress = placemark.addressDictionary! as NSDictionary
let userDefaults = UserDefaults.standard
userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)
// For getting data from NSDictionary.
//用于从NSDictionary获取数据。
let userDefaults = UserDefaults.standard
let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary