将[Int:String]字典存储到user.defaults会因SIGABRT错误而崩溃 [英] storing [Int:String] dictionaries to user.defaults crashes with SIGABRT error

查看:95
本文介绍了将[Int:String]字典存储到user.defaults会因SIGABRT错误而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用user.default保存一堆数据.除了一个字典[Int:String],其他所有内容都可以保存.有趣的部分是,我可以很好地保存字典[String:Int],但是当它的[Int:String]运行运行包含代码的保存函数时,它就会崩溃.

saving a bunch of data using user.default. everything saves fine except one dictionary [Int:String]. The funny part is this, I can save a dictionary [String:Int] fine, but as soon as its [Int:String], it crashes when I run my save function that has my code in it.

控制台显示以下内容:

***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'试图插入非属性列表对象{ 99 =詹妮弗; }作为关键玩家名称"

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object { 99 = Jennifer; } for key playernames'

谢谢

推荐答案

您要保存在UserDefualt中的对象的类型必须为NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary.根据苹果文档:

The Object that you are trying to save in the UserDefualt must be of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. As per apple docs:

默认对象必须是属性列表-即(或 对于集合,是NSData,NSString, NSNumber,NSDate,NSArray或NSDictionary.如果你想存储任何 其他类型的对象,通常应将其归档以创建一个 NSData的实例. UserDefault文档

A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. UserDefault Documentation

NSDictionary的密钥是符合NSCopying协议的字符串或类型.

The key of NSDictionary is a string or a type conforming to NSCopying protocol.

您可以尝试以下操作:

let yourData = NSKeyedArchiver.archivedDataWithRootObject(yourDictionary)
let userDefualts = UserDefaults.standard
userDefualts.set(yourData, forKey: "yourKey")

这篇关于将[Int:String]字典存储到user.defaults会因SIGABRT错误而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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