我正在从FireBase提取数据并将其保存在我的领域内,但无法正常工作:

for doc in docs {
    let shopData = doc.data()
    let newShop = RLMShop()
    newShop.shopName = shopData["name"] as? String ?? "Empty Name"
    self.saveShop(shop: newShop) // My issue is here
}

我的saveShop函数:
    func saveShop(shop: RLMShop) {
       do {
          try realm.write {
            realm.add(shop)
          }
       } catch {
        print("Error saving shop \(error)")
    }
}

调用保存功能不会保存我的对象。

最佳答案

您遇到的问题是您正在创建RLMShop对象,但未将其链接到RLMShopsCategory对象,因此shopsList将不包含新对象。

// Fetch the RLMShopsCategory that you wish to add the RLMShop too
// Using Primary Key here just as an example
let shopsCategory = realm.object(ofType: RLMShopsCategory.self, forPrimaryKey: "YourKey")

for doc in docs {
    let shopData = doc.data()
    let newShop = RLMShop()
    newShop.shopName = // setting the properties etc

    // This is the part you are missing
    // You need to append the newShop to your shopsCategory object
    try! realm.write {
       shopsCategory.shopsList.append(newShop)
    }
}

10-08 12:20