在我的应用程序中,我尝试同时使用 MagicalRecord + AFNetworking + NSFetchedResultsController 来同步数据并在地图或 tableView 中动态显示它。
让我们看一些下载方法的代码:
+ (void) getDataWithCompletionBlock: (void (^)(void)) block {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL_GET_DATA]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
for (NSDictionary *dict in JSON) {
[MyModel createOrUpdateMyModelFromDict:[dict mutableCopy]];
}
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveInBackgroundCompletion:^{
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveNestedContexts];
block();
}];
});
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
DDLogError(@"getDataWithCompletionBlock FAILURE: %@", error);
}];
[operation start];
}
我使用 下载数据AFJSONRequestOperation
,然后使用 GCD 和后台线程创建模型,保存当前线程的上下文并执行successBlock
(MagicalRecord 在successBlock
上运行dispatch_get_main_queue()
,因此在 GUI 线程中调用它。
这个同步模型好吗?因为有时(在真实设备上比在模拟器上更常见)我会收到一些错误,NSFetchedResultsController
例如“索引处没有对象:在索引部分:”或“CoreData 无法完成故障......”。
他们都认为,Core Data 和多线程环境有问题。有没有人尝试将所有这三个工具连接起来一起工作?如果是这样,我错过了什么?对于该架构,您是否有任何运行良好的代码示例?