How to set Dictionary in NSUserDefault in swift?

后端 未结 1 1824
执笔经年
执笔经年 2021-01-25 14:34

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 = [:]
               


        
相关标签:
1条回答
  • 2021-01-25 14:44

    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]
    
    0 讨论(0)
提交回复
热议问题