如何在Firebase中保存复杂的对象?

时间:2019-03-06 08:04:11

标签: swift firebase

我有2节课。 用户类,其中包含 Item 类的对象数组。我想在Firebase中保存用户的对象。我该怎么办?

class User: NSObject {
    var name: String
    var items: [Item]
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
    }
}

class Item{
    var name: String
    init(name: String) {
        self.name = name
    }
}

var user = User(dictionary: [:])
user.name = "Tom"

var item = Item(name: "item1")
user.items.append(item)

let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("users").child(uid).setValue(user)

1 个答案:

答案 0 :(得分:1)

将它们另存为Firebase对象。

class User: NSObject {
    var name: String
    var items: [Item]
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
    }
    var json: [String: Any] {
        return ["name": name, "items": items.map { $0.json }]
    }
}

class Item{
    var name: String
    init(name: String) {
        self.name = name
    }
    var json: [String: Any] { 
        return ["name": name]
    }
}

Database.database().reference().child("users").child(uid).setValue(user.json)