ios - 更新 Firebase 会删除现有数据

标签 ios objective-c firebase

我正在使用 Firebase 构建一个应用程序,最近我使用这段代码来更新用户词典中“帖子”的列表/词典。看一看:

Firebase *baseRef = [[Firebase alloc] initWithUrl:@"https://<MY-APP>.firebaseio.com"];

NSString *userPostsPath = [NSString stringWithFormat:@"users/%@/posts", userId];

NSDictionary *postRef = @{ postId : postDescription };

[baseRef updateChildValues:@{
                             userPostsPath : postRef
                             // here I'd have a similar update
                             }withCompletionBlock:^(NSError *error, Firebase *ref) {
                                 handler(error, ref);
                             }];

这适用于第一次更新,但我第二次这样做时,所有现有的帖子都被删除了。但是,将代码更改为:

Firebase *baseRef = [[Firebase alloc] initWithUrl:@"https://tonightdb.firebaseio.com"];

NSString *usersPostsPath = [NSString stringWithFormat:@"users/%@/posts/%@/", userId, postId];

[baseRef updateChildValues:@{
                             usersPostsPath : postDescription,
                             // similar update path
                             }withCompletionBlock:^(NSError *error, Firebase *ref) {
                                 handler(error, ref);
                             }];

正确更新 Firebase。

两者有什么区别?为什么第一个不起作用?

编辑

是否可以这样做:

Firebase *baseRef = [[Firebase alloc] initWithUrl:@"https://<MY-APP>.firebaseio.com"];
NSString *newKey = [baseRef childByAutoId];

然后使用该 key 执行如下所示的更新:

[baseRef updateChildValues:@{
                           [NSString stringWithFormat:@"/posts/%@/", newKey] : // something
                           [NSString stringWithFormat:@"/posts/%@/members/<something>", newKey] : // something
withCompletionBlock:^(NSError *error, Firebase *ref) {
            handler(error, ref, task);
        }];

基本上是在同一请求中对同一路径发出多个更新,事先不存在,同时避免覆盖问题

最佳答案

您的第一个示例转化为更新指令:

"users/posts" = { "postid1": postDescription }

第二个例子翻译成:

"users/posts/postid1" = postDescription

作为一个计算机程序,Firebase 服务器对您提供的指令进行非常字面的解释。它接受每个更新指令并将路径中的数据(= 之前的部分)替换为值(= 之后的部分)。

知道这一点后,您可以看到在第二个示例中它将在 users/posts/postid1 处写入 postDescription。这将替换该帖子的现有描述,但这可能是您想要的。

第二个示例在 users/posts 处写入 { "postid1": postDescription }。这将替换该位置的现有值,因此您实际上是用新的/更新的帖子替换所有现有帖子。这可能不是您想要的。

更新

如果您要创建一个新对象并将 key 散布到多个位置,您可以利用 childByAutoId 是纯客户端操作这一事实:

let newRef = ref.childByAutoId()
let newKey = newRef.key
ref.childByAppendingPath("child1").childByAppendingPath(newKey).setValue("one")
ref.childByAppendingPath("child2").childByAppendingPath(newKey).setValue("two")

关于ios - 更新 Firebase 会删除现有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35286354/

相关文章:

ios - Objective-C读取十六进制代码并输出表情符号

iOS NSURLAuthenticationMethodClientCertificate 未请求与 ActiveSync 服务器

ios - 使用 NSXMLParser 从 XML 中检索图像

android - FCM 中的 token 更新

json - Firebase 数据库 - 编码错误

ios - 如何在导航栏动画期间删除不需要的黑色区域。屏幕截图

ios - NSURLRequest 产生与 HTTP 代理客户端不同的结果

ios - 更多按钮在 tabbbaritem 中不可见

objective-c - 从 NSXMLElement 获取属性的对应值

firebase - 将Firebase连接到我的TextField/ Material 登录页面代码