如何保存字符串到NSUserDefaults?


当前回答

[nsusudefaults默认:aString forKey:aKey]

其他回答

对于Swift,我创建了两个函数,它们将从首选项中保存和检索值。

这对你很有帮助。

//保存对象

static func setObject(value:AnyObject ,key:String)
{
    let pref = NSUserDefaults.standardUserDefaults()
    pref.setObject(value, forKey: key)
    pref.synchronize()
}

static func getObject(key:String) -> AnyObject
{
    let pref = NSUserDefaults.standardUserDefaults()
    return pref.objectForKey(key)!
}
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

然后再拿回来

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

[nsusudefaults默认:aString forKey:aKey]

更准确地说

-(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
}