【问题标题】:Retrieving and using a value from Firebase in Objective-C在 Objective-C 中检索和使用 Firebase 中的值
【发布时间】:2020-05-12 22:19:49
【问题描述】:

我正在尝试从 Firebase 检索值,然后对它们执行操作。但是,似乎这些值仅在函数调用内部分配。我的代码如下所示:

self.ref = [[FIRDatabase database] reference];

[[_ref child:@"user"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
      // Get all user wishlists
        self.wishLists = [[NSMutableDictionary alloc] initWithDictionary:snapshot.value[@"wishlist"]];

        NSLog(@"%@", self.wishLists);

    } withCancelBlock:^(NSError * _Nonnull error) {
      NSLog(@"%@", error.localizedDescription);
    }];

    NSLog(@"%@", self.wishLists);

    for(id key in self.wishLists){
        wishList *newList = [wishList new];
        newList.name = key;
        NSLog(@"%@", newList.name);
        [self.listArray addObject:newList];
    }

其中 self.wishLists 定义如下: @property (strong) NSMutableDictionary *wishLists; 第一个 NSLog 调用 print wishList 成功地打印出该值,但第二个没有,这表明 self.wishLists 以某种方式为空,即使我将它分配给我从 Firebase 中提取的值。如何保持在函数之外分配的值?

【问题讨论】:

  • 任何需要访问数据库数据的代码都需要在完成处理程序中(当数据可用时调用),或者从完成处理程序中调用。

标签: objective-c firebase firebase-realtime-database


【解决方案1】:

数据是从 Firebase 异步加载的,因为它可能需要来自服务器。发生这种情况时,您的主代码会继续执行,因此不会阻止用户使用该应用程序。然后在加载数据时,将调用您的完成处理程序。

因此,任何需要访问数据库数据的代码都需要在完成处理程序中(当数据可用时调用),或者从完成处理程序中调用。

所以解决问题的最简单方法是将循环移动到完成处理程序中:

self.ref = [[FIRDatabase database] reference];

[[_ref child:@"user"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
      // Get all user wishlists
        self.wishLists = [[NSMutableDictionary alloc] initWithDictionary:snapshot.value[@"wishlist"]];

        NSLog(@"%@", self.wishLists);

        NSLog(@"%@", self.wishLists);

        for(id key in self.wishLists){
            wishList *newList = [wishList new];
            newList.name = key;
            NSLog(@"%@", newList.name);
            [self.listArray addObject:newList];
        }

    } withCancelBlock:^(NSError * _Nonnull error) {
      NSLog(@"%@", error.localizedDescription);
    }];

如果您想将加载数据的代码与使用它的代码分开,您也可以定义自己的完成处理程序。有关示例,请参阅getting data out of a closure that retrieves data from firebase

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多