swift - 如何在 NSUserDefault 中快速设置字典?

标签 swift nsdictionary nsuserdefaults nsmutabledictionary sigabrt

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

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

但是我得到一个错误:

Thread 1: signal SIGABRT

我不知道为什么。

最佳答案

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

关于它的文档有两个。

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 的值。您必须像这样使用字符串作为 key :

myDic = ["1": 2]

关于swift - 如何在 NSUserDefault 中快速设置字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264994/

相关文章:

ios - NSMutableDictionary isKindOfClass NSDictionary 为 false

ios - 如何将元组字典保存和读取到 NSUserDefaults?

ios - 替换 CloudKit 记录时遇到问题

ios - Swift - 使用 Codeable 保存对象会导致应用程序崩溃

swift - 在开始时创建数百个 UIImage 并让它们在 Swift 中的任何位置可用的最佳方法是什么?

ios - 设置 UIProgressView 的最大值(swift 4)

ios - NSDictionary objectForKey 返回错误值

iphone - NSDictionary 添加 NULL 键值

ios - NSInternalInconsistencyException : There can only be one UIApplication instance

ios - 如何在不按下按钮的情况下在 Apple Watch 中开始和停止听写