如何快速在 NSUserDefault 中设置字典? [英] How to set Dictionary in NSUserDefault in swift?
问题描述
我有一个可变字典(以 [Int:Int] 的形式)并希望它能够保存它.我会像这样使用 NSUserDefaults:
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")
但是我得到一个错误:
线程 1:信号 SIGABRT
Thread 1: signal SIGABRT
我不知道为什么.
推荐答案
setObject(_:forKey:)
can't accept Dictionary
with a key which is integer type.该方法需要属性列表对象,但 myDic = [1:2]
不是属性列表对象.
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.
关于它的文件有两个.
NSUserDefaults 的 setObject(_:forKey:)
value
参数只能是属性列表对象:NSData
,NSString
、NSNumber
、NSDate
、NSArray
或 NSDictionary
.为了NSArray
和 NSDictionary
对象,它们的内容必须是属性列出对象.
The
value
parameter can be only property list objects:NSData
,NSString
,NSNumber
,NSDate
,NSArray
, orNSDictionary
. ForNSArray
andNSDictionary
objects, their contents must be property list objects.
虽然 NSDictionary
和 CFDictionary
对象允许它们的键是任何类型的对象,如果键不是字符串对象,则集合不是属性列表对象.
And although
NSDictionary
andCFDictionary
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
的值.您必须像这样使用字符串作为键:
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]
这篇关于如何快速在 NSUserDefault 中设置字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!