How to set Dictionary in NSUserDefault in swift?

房东的猫 提交于 2019-12-02 08:16:30

问题


I've a mutable dictionary (in form of [Int:Int]) and want that to save it. I would use NSUserDefaults like that:

    var myDic: NSMutableDictionary = [:]
        myDic = [1:2]
        NSUserDefaults.standardUserDefaults().setObject(myDic, forKey: "myDic")

but with that I get an error:

Thread 1: signal SIGABRT

I have no idea why.


回答1:


setObject(_:forKey:) can’t accept Dictionary with a key which is integer type. The method requires property-list objects, but myDic = [1:2] is not property-list object.

There are two documents about it.

setObject(_:forKey:) of NSUserDefaults

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects.

About Property Lists

And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

If you set a integer-key to Dictionary, the Dictionary object cannot be used for a value of setObject. You have to use a string for the key like this:

myDic = ["1": 2]


来源:https://stackoverflow.com/questions/35689828/how-to-set-dictionary-in-nsuserdefault-in-swift

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