iOS中的Firebase updateChildValues,还有什么更优化的?

时间:2018-11-08 15:31:00

标签: ios swift firebase firebase-realtime-database

我使用iPhone应用程序(Swift 4),同时在几个节点上对数据库进行了一些更新。

以下两种方法都可以,但是我想知道最“干净”的方法是什么?

方法1:

 let idNotification = BaseViewController.database.child("notifications").childByAutoId().key
        BaseViewController.database.child("notifications").child(idNotification).updateChildValues(["content" : "some content"])
        BaseViewController.database.child("users").child(userID).child("notifications").updateChildValues(["something" : true])

方法2:

    let idNotification = BaseViewController.database.child("notifications").childByAutoId().key
    let createNotif = ["content" : "some content"]
    let notifToUser = ["something" : true]
    BaseViewController.database.updateChildValues(["/notifications/\(idNotification)" : createNotif, "/users/\(userID)/notifications" : notifToUser])

如果发生崩溃,那有什么区别吗?对于第一个,如果两个更新请求之一失败,则另一个不会受到影响。如果仅两个失败之一,方法2会发生什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

第一个代码段向数据库发送了多个写操作(每个对updateChildValues的调用都包含一个写操作)。第二个片段仅发送一个写操作。

两者都是完全有效的,并且两者都可能是您想要的。例如,如果两个更新之间没有关系,则分开发送它们是有意义的。但是,如果更新是相关的,那么一次发送它们就更有意义了,因为这样一来,数据库的安全规则就可以一次写入操作来允许/拒绝它们。