如何保存字符串到NSUserDefaults?


当前回答

就像这样:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

然后检索:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

你应该看看苹果的NSUserDefaults类参考,也可以看看这个教程:iPhone编程教程-使用NSUserDefaults保存/检索数据

其他回答

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
}
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

然后再拿回来

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

[nsusudefaults默认:aString forKey:aKey]

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

NSString* const TIME_STAMPS_KEY = @"TIME_STAMPS_KEY";

对于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)!
}