Objective C - Firebase - 如何将完成处理程序添加到 FDataSnapshot

Objective C - Firebase - How to add completion handler to FDataSnapshot

我正在尝试使用 Firebase FDataSnapshot 来提取数据,我希望它使用 MagicalRecord 将其数据写入我的核心数据。

根据 Firebases "best practice" 博客,我需要保留对 "handle" 的引用,以便稍后清理。此外,他们提到将 FDSnapshot 代码放在 viewWillAppear.

我想要一个回调,这样当它完成更新核心数据的工作时。

但我真的很清楚该怎么做;它做两件事并同时给出 return。

// In viewWillAppear:

__block NSManagedObjectContext *context = [NSManagedObjectContext MR_context];

    self.handle = [self.ref observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
        if (snapshot.value == [NSNull null])
        {
            NSLog(@"Cannot find any data");
        }
        else
        {
            NSArray *snapshotArray = [snapshot value];

// cleanup to prevent duplicates
               [FCFighter MR_truncateAllInContext:context];

            for (NSDictionary *dict in snapshotArray)
            {

                FCFighter *fighter = [FCFighter insertInManagedObjectContext:context];
                fighter.name = dict[@"name"];

                [context MR_saveToPersistentStoreWithCompletion:^(BOOL contextDidSave, NSError *error){
                    if (error)
                    {
                        NSLog(@"Error - %@", error.localizedDescription);
                    }
                }];
            }
        }
    }];

    NSFetchRequest *fr = [[NSFetchRequest alloc] initWithEntityName:[FCFighter entityName]];
    fr.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
    self.fighterList = (NSArray *) [context executeFetchRequest:fr error:nil];
    [self.tableView reloadData];

上述代码中,核心数据读取没有等待firebase完成。

因此,我的查询 -- 我如何最好地组合完成处理程序,以便在完成时更新核心数据并重新加载表视图。

非常感谢

这是处理异步数据时的常见问题。

最重要的是,所有从异步调用(在本例中为快照)返回的数据处理都需要在块内完成。

任何块之外所做的事情都可能发生在数据返回之前。

所以一些 sudo 代码

observeEvent  withBlock { snapshot
     //it is here where snapshot is valid. Process it.
     NSLog(@"%@", snapshot.value)
}

哦,还有一个旁注。当您稍后要用它做其他事情时,您真的只需要跟踪句柄引用。除此之外,你可以忽略句柄。

所以这是完全正确的:

[self.ref observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
   //load your array of tableView data from snapshot
   //  and/or store it in CoreData
   //reload your tableview
}