1

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

根据 Firebase 的“最佳实践”博客,我需要保留对“句柄”的引用,以便以后对其进行清理。此外,他们提到将 FDSnapshot 代码放入viewWillAppear.

我想要一个回调,以便当它完成更新核心数据的事情时。

但我真的很清楚如何做到这一点;它做两件事并同时给予回报。

// 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 完成。

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

非常感谢

4

1 回答 1

1

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

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

在数据返回之前,在块完成的任何事情都可能发生。

所以一些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
}
于 2016-01-25T22:55:42.960 回答