如何在 swift 的 NSUserDefault 中设置 Dictionary?

How to set Dictionary in NSUserDefault in swift?

我有一个可变字典(以 [Int:Int] 的形式)并希望保存它。我会像那样使用 NSUserDefaults:

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

但是我得到一个错误:

Thread 1: signal SIGABRT

我不知道为什么。

setObject(_:forKey:) 不能接受整数类型的键 Dictionary。该方法需要 属性-list 对象,但 myDic = [1:2] 不是 属性-list 对象。

关于它的文档有两个。

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.

如果将整数键设置为 Dictionary,则 Dictionary 对象不能用于值 setObject。您必须像这样使用字符串作为密钥:

myDic = ["1": 2]