如何快速在 NSUserDefault 中设置字典? [英] How to set Dictionary in NSUserDefault in swift?

查看:90
本文介绍了如何快速在 NSUserDefault 中设置字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变字典(以 [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 参数只能是属性列表对象:NSDataNSStringNSNumberNSDateNSArrayNSDictionary.为了NSArrayNSDictionary 对象,它们的内容必须是属性列出对象.

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.

关于属性列表

虽然 NSDictionaryCFDictionary 对象允许它们的键是任何类型的对象,如果键不是字符串对象,则集合不是属性列表对象.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆