将字符串保存到NSUserDefaults?

如何将字符串保存到NSUserDefaults


NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

以后再拿回来

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

更确切地说

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

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

以下是如何对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") {

}
链接地址: http://www.djcxy.com/p/85169.html

上一篇: Save string to the NSUserDefaults?

下一篇: How to store custom objects in NSUserDefaults