Swift 3是存储具有数组等的Object的最佳方式

时间:2017-04-18 08:38:28

标签: swift

我开始使用Swift 3开发并且我变得疯狂。以下情况:

(state) => ({
 query: state.routing.locationBeforeTransitions.query.q,
 results: state.userResults,
 searchInFlight: state.searchInFlight
})

哪种方式是持久存储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 data : [mainObject].plist

抱歉,但我的英语更糟。

1 个答案:

答案 0 :(得分:0)

无法使用

NSCoding,因为这些类不是NSObject的子类。

由于两个类中的所有属性都符合属性列表,因此您可以添加计算属性propertyListRepresentation和适当的初始化程序。

类名应该以大写字母开头,以下划线开头的参数在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)