如何保存字符串到NSUserDefaults?


当前回答

用于保存:

[[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"KTerminated"];
[[NSUserDefaults standardUserDefaults]synchronize];

对于检索使用这个:

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];

其他回答

更准确地说

-(void)saveToUserDefaults:(NSString*)myString
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"timestamps"];
        [standardUserDefaults synchronize];
    }
}

在Swift 4.0.3 Xcode 9

============set  Data in UserDefaults =========

  UserDefaults.standard.set(userName, forKey: "userName")
  UserDefaults.standard.synchronize()

============Get Data in UserDefaults =========

  let userName = UserDefaults.standard.string(forKey: "userName")
  print(userName ?? "Gera")

  userNameTextField.text = ""+userName!

下面是如何对Swift做同样的事情;

var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")

以后把它拿回来;

if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
    // Do something with savedValue
}

在Swift 3.0中

var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")

if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {

}

在Swift5和Xcode 10.2中

//Save
UserDefaults.standard.set(true, forKey: "Key1") //Bool
UserDefaults.standard.set(1, forKey: "Key2")  //Integer
UserDefaults.standard.set("This is my string", forKey: "Key3") //String
UserDefaults.standard.synchronize()
        
//Retrive
UserDefaults.standard.bool(forKey: "Key1")
UserDefaults.standard.integer(forKey: "Key2")
UserDefaults.standard.string(forKey: "Key3")
            
//Remove
UserDefaults.standard.removeObject(forKey: "Key3")

注意:保存文本数据(意味着字符串,数组,字典等)在UserDefaults。

不要将图片保存在UserDefaults中,不推荐(保存图片在本地目录)。

[nsusudefaults默认:aString forKey:aKey]