如何保存字符串到NSUserDefaults?
当前回答
斯威夫特更新了:
let userID = "BOB"
宣布userDefaults:
let defaults = UserDefaults.standard
defaults.setValue(userID, forKey: "userID")
并得到它:
let userID = defaults.object(forKey: "userID")
其他回答
[nsusudefaults默认:aString forKey:aKey]
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
检索
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];
就像这样:
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做同样的事情;
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") {
}
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];
然后再拿回来
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"preferenceName"];
推荐文章
- 如何精确地以毫秒为单位记录方法的执行时间?
- 在整个UIWindow中获取UIView的位置
- 如何解散ViewController在Swift?
- 保存字符串到NSUserDefaults?
- 如何将JSON字符串转换为字典?
- 什么是NSLocalizedString等效在Swift?
- 查看保存的NSUserDefaults的简单方法?
- 如何创建一个字符串的格式?
- 如何添加UITableViewCell之间的间距
- 电话:用于文本输入的数字键盘
- 在为设备编译时,Apple Mach-O连接器错误
- 获取最顶端的UIViewController
- 使用isKindOfClass与Swift
- SourceKitService终止
- 如何从iPhone应用程序发送邮件