我正在尝试使用Firebase的FDataSnapshot
来提取数据,我希望它能够使用MagicalRecord将其数据写入我的核心数据。
根据Firebases"最佳实践"博客我需要继续引用"句柄"所以它可以在以后清理。此外,他们还提到将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时。
非常感谢
答案 0 :(得分: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
}