问题描述
我有以下测试代码:
func testSaveDictionary() {
let userDefaults = NSUserDefaults.standardUserDefaults()
var jo = [
"a" : "1.0",
"b" : "2.0"
]
let akey = "aKey"
userDefaults.setObject(jo, forKey: akey)
var isOk = userDefaults.synchronize()
var data0 = userDefaults.dictionaryForKey(akey)
println(data0)
}
println(data0)的输出为零。
The output of println(data0) is nil.
我的代码有什么问题吗? Swift Dictionary是否现在或在最终版本中被列为属性列表?
Anything wrong with my code? Is Swift Dictionary considered property list now or in the final release?
推荐答案
更新 Swift 2,Xcode 7: / strong>由于@atxe注意到,NSUserDefaults字典现在映射为 [String,AnyObject]
。这是Objective-C轻量级泛型的
结果,它允许
将Objective-C方法声明为
Update for Swift 2, Xcode 7: As @atxe noticed, NSUserDefaults dictionaries are now mapped as [String, AnyObject]
. This is aconsequence of the Objective-C "lightweight generics" which allowto declare the Objective-C method as
- (NSDictionary<NSString *,id> *)dictionaryForKey:(NSString *)defaultName
(默认对象必须是属性列表,特别是字典
键只能是字符串。)
(Default objects must be property lists and in particular the dictionarykeys can only be strings.)
另一方面,Swift字典被桥接如果可能的话可以自动进行,所以来自问题的原始代码工作(再次):
On the other hand, a Swift dictionary is bridged automatically if possible, so the original code from the question works (again):
let jo = [
"a" : "1.0",
"b" : "2.0"
]
let akey = "aKey"
// Swift 2:
userDefaults.setObject(jo, forKey: akey)
// Swift 3:
userDefaults.set(jo, forKey: akey)
Swift 1.2的原始答案
用户默认值可以存储 NSDictionary
对象。这些映射到Swift
作为 [NSObject:AnyObject]
:
Original answer for Swift 1.2:The user defaults can store NSDictionary
objects. These are mapped to Swiftas [NSObject : AnyObject]
:
var jo : [NSObject : AnyObject] = [
"a" : "1.0",
"b" : "2.0"
]
userDefaults.setObject(jo, forKey: akey)
var isOk = userDefaults.synchronize()
请注意, code> dictionaryForKey()返回一个可选项,所以你应该检查一下
,例如可选的分配:
And note that dictionaryForKey()
returns an optional, so you should check itfor example with an optional assignment:
if let data0 = userDefaults.dictionaryForKey(akey) {
println(data0)
} else {
println("not set")
}
// Output: [b: 2.0, a: 1.0]
这篇关于Swift NSUserDefaults不保存字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!