无法从NSUserDefaults获取字典作为保存格式

时间:2015-09-29 15:48:49

标签: swift dictionary nsuserdefaults

我希望从NSUserDefaults获取一个快速字典作为我之前保存的格式。我已将字典保存为[String:String]格式,但在我使用dictionaryForKey(key)方法获取字典时,我得到[String:AnyObject]?。如何将[String:AnyObject]?转换为[String:String]或如何以正确的格式获取字典?

保存到NSUserDefaults

var tasks: Dictionary<String,String> = [:]
let defaults = NSUserDefaults.standardUserDefaults()
let key = "key"
defaults.setObject(tasks, forKey: key)
defaults.synchronize()

NSUserDefaults

获取
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingArray = defaults.dictionaryForKey(key)

1 个答案:

答案 0 :(得分:2)

如果您使用默认值注册了它,那么它永远不会是nil,只需将其向下转换为正确的类型

let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingDictionary = defaults.objectForKey(key) as! Dictionary<String,String>