如何在 NSUserDefaults 中保存一个对象数组? [英] How to save in NSUserDefaults a array of object?
问题描述
我需要在 NSUserDefaults
中保存一个数组或其他数据结构来保存具有这种格式的对象:
I need save in NSUserDefaults
an array or other structure of data to save objects with this format:
name = "myName", lastName = "myLastName"
我试图用一组数组来做这件事,但这不能保存在 NSUserDefaults
中.
I was trying to do this with an array of arrays but this can't save in NSUserDefaults
.
现在我正在尝试使用具有结构的自定义类来创建对象并附加到数组,但在尝试将其保存到 NSUserDefaults
时也会出错.我需要用这种结构保存,但我不知道什么是正确的形式.我该怎么做?
Now I am trying with a custom class with structure to create objects and append to the array, but also get an error when trying to save this to NSUserDefaults
. I need save with this structure, but I don't know what is the correct form. How would I do this?
var taskMgr: TaskManager = TaskManager()
struct task {
var name = "Un-Named"
var lastName = "Un-lastNamed"
}
class TaskManager: NSObject {
var tasks : [task] = []
func addTask(name : String, lastName: String){
tasks.append(task(name: name, lastName: desc))
}
}
推荐答案
NSUserDefaults
期望存储的对象都是属性列表对象,即 NSArray
的实例,NSDictionary
、NSString
、NSNumber
、NSData
或 NSDate
.您的结构不是其中之一.在存储对象之前,您需要将对象转换为属性列表类型.一种方法是使用 NSKeyedArchiver
和 NSCoding
协议将您的结构写入 NSData
的实例.
NSUserDefaults
expects the stored objects to all be property list objects, i.e. instances of NSArray
, NSDictionary
, NSString
, NSNumber
, NSData
, or NSDate
. Your struct isn't one of those. You'll need to convert your objects to property list types before you store them. One way to do that is to use NSKeyedArchiver
and the NSCoding
protocol to write your structs into an instance of NSData
.
这篇关于如何在 NSUserDefaults 中保存一个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!