如何在NSUserDefault swift中保存/检索嵌套字典?

时间:2021-05-08 13:20:56

I'm building an app, in which the user is able to create UITableviewcell that will lead to a different UIViewController editable by the user. I save the user information as such:

我正在构建一个应用,用户可以在其中创建UITableviewcell这会导致用户创建一个不同的UIViewController可编辑。我将用户信息保存如下:

level1Dictionary = [String : [String : String]]() If the user names a UITableViewCell Dog they segue to the viewController and i set level1Dictionary[dog] = [String : String]() I now save the dictionary in NSUserdefaults as such NSUserDefaults.StandardUserDefaults()setObject(level1Dictionary, forKey: "level1Dictionary") All works fine.

level1Dictionary = [String: [String: String]]()如果用户给UITableViewCell命名他们会segue到viewController,我设置了level1Dictionary[Dog] = [String: String]

When i restart the app and press my customCreate UITAbleViewCell named dog i want to retrieve what ever information the user stored in level1Dictionary = [Dog : [String : String]]. I retrieve the information as such within viewdidload: level1Dictionary = NSUserDefault.standardUserDefaults().objectForKey("level1Dictionary") as? [String : String] ?? [String : String]() but this returns error: Cannot Convert value of type [String : String]? to expected argument type [String : [String : String]]?

当我重新启动应用程序并按下我的customCreate UITAbleViewCell命名的狗时,我想要检索用户在level1Dictionary = [dog: [String: String]]中存储的信息。我在viewdidload中检索这样的信息:level1Dictionary = NSUserDefault.standardUserDefaults().objectForKey(“level1Dictionary”)as?(字符串:字符串)? ?[String: String]()但此返回错误:无法转换类型[String: String]的值?对预期参数类型[String: [String: String]]?

1 个解决方案

#1


1  

Try this:

试试这个:

NSUserDefault.standardUserDefaults().objectForKey("level1Dictionary") as? [String : [String : String]]?? [String : [String : String]]()

#1


1  

Try this:

试试这个:

NSUserDefault.standardUserDefaults().objectForKey("level1Dictionary") as? [String : [String : String]]?? [String : [String : String]]()