storing [Int:String] dictionaries to user.defaults crashes with SIGABRT error

不羁的心 提交于 2019-12-01 12:02:06

问题


saving a bunch of data using user.default. everything saves fine except one dictionary [Int:String]. The funny part is this, I can save a dictionary [String:Int] fine, but as soon as its [Int:String], it crashes when I run my save function that has my code in it.

the console shows the follow:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object { 99 = Jennifer; } for key playernames'

thank you


回答1:


The Object that you are trying to save in the UserDefualt must be of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. As per apple docs:

A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. UserDefault Documentation

The key of NSDictionary is a string or a type conforming to NSCopying protocol.

You can try this:

let yourData = NSKeyedArchiver.archivedDataWithRootObject(yourDictionary)
let userDefualts = UserDefaults.standard
userDefualts.set(yourData, forKey: "yourKey")


来源:https://stackoverflow.com/questions/51961089/storing-intstring-dictionaries-to-user-defaults-crashes-with-sigabrt-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!