Swift 3是使用数组等存储对象的最佳方式
我开始使用Swift 3进行开发,我快疯了。以下情况:Swift 3是使用数组等存储对象的最佳方式,swift,Swift,我开始使用Swift 3进行开发,我快疯了。以下情况: class subObject { var name : String var list : [Int] init( _name : String, _list : [Int] ){ self.name = _name self.list = _list } } class mainObject { var subObjectList : [subObject] init( _list :
class subObject
{
var name : String
var list : [Int]
init( _name : String, _list : [Int] ){
self.name = _name
self.list = _list
}
}
class mainObject
{
var subObjectList : [subObject]
init( _list : [subObject] ){
self.subObjectList = _list
}
}
var data : [mainObject]
哪种方法是最先进的持久存储var数据:[mainObject]
。我已经尝试了.plist
和NSKeyedArchiver
,但没有成功
抱歉,我的英语更差。
NSCoding
无法使用,因为这些类不是NSObject
的子类
由于这两个类中的所有属性都与属性列表兼容,因此可以添加计算属性propertylisterepresentation
和适当的初始值设定项
类名称应该以大写字母开头,参数以下划线开头在Swift中是不常见的
class SubObject
{
var name : String
var list : [Int]
init(name : String, list : [Int] ){
self.name = name
self.list = list
}
init?(dictionary : [String:Any]) {
guard let name = dictionary["name"] as? String,
let list = dictionary["list"] as? [Int] else { return nil }
self.name = name
self.list = list
}
var propertyListRepresentation : [String:Any] {
return ["name" : name, "list" : list]
}
}
class MainObject
{
var subObjectList : [SubObject]
init(list : [SubObject] ){
self.subObjectList = list
}
init(propertyList : [[String:Any]] ){
self.subObjectList = propertyList.flatMap{ SubObject(dictionary: $0) }
}
var propertyListRepresentation : [[String:Any]] {
return subObjectList.map{ $0.propertyListRepresentation }
}
}
要使用它:
let subs = [SubObject(name: "Foo", list: [1, 2, 3]), SubObject(name: "Bar", list: [4, 5, 6])]
let main = MainObject(list: subs)
let list = main.propertyListRepresentation
let data = try! PropertyListSerialization.data(fromPropertyList: list, format: .xml, options: 0)
print(String(data:data, encoding: .utf8)!)
let restoredList = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
let restoredMain = MainObject(propertyList: restoredList)
你能提供更多关于你面临的问题的信息吗??您想将
子对象列表
作为子对象数组吗?请尝试var subObjectList:array
您在NSUserDefault中遇到了哪些问题?这是一种存储数据的明确方式,因此可能值得再次访问。核心数据是存储数据的另一种方式,可能具有更陡峭的学习曲线。@JackyShek没有区别:Array
和[subObject]
是同义词。@JackyShek没有。Array
与[Class]
相同,这只是语法上的糖分,声明是一样的。除非您仍在使用Swift 1.1,否则不可能拥有一个而不拥有另一个。