如何保存字符串到NSUserDefaults?


当前回答

一个好的做法是使用一个常量作为键,以避免在不存储和读取相同键的情况下出现错误

NSString* const TIME_STAMPS_KEY = @"TIME_STAMPS_KEY";

其他回答

不要忘记这句话,否则它可能并不总是有效:

[standardUserDefaults synchronize];

更准确地说

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

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

Swift 3更新

func setObject(value:AnyObject ,key:String)
{
    let pref = UserDefaults.standard
    pref.set(value, forKey: key)
    pref.synchronize()
}

func getObject(key:String) -> AnyObject
{
    let pref = UserDefaults.standard
    return pref.object(forKey: key)! as AnyObject
}

[nsusudefaults默认:aString forKey:aKey]

用于保存:

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

对于检索使用这个:

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