【发布时间】:2012-12-16 01:54:23
【问题描述】:
将我的 Core Data 架构与提供 JSON 的远程 API 同步的最佳方式是什么?目前,我正在遍历 JSON 响应中的每个字典,检查 Core Data 以查看 API ID 是否存在。
这很好用,但现在剩下要做的就是删除所有不在服务器上的本地对象。这是我的 JSON 数据示例:
[
{
"id":1234,
"name":"My first object",
"description":"This is a long string with lots of information"
},
{
"id":1235,
"name":"My second object",
"description":"This is a long string with lots of information"
}
]
目前我能想到的唯一方法如下:
NSArray *jsonData = // Convert json data to array using NSJSONSerialization
NSInteger fetchedCount = _fetchedResultsController.fetchedObjects.count;
if (fetchedCount != jsonData.count) {
for (int i = 0; i < fetchedCount; i++) {
NSManagedObject *object = [_fetchedResultsController objectAtIndexPath: [NSIndexPath indexPathForItem:i
inSection:0]];
NSNumber *idNumber = object.apiID;
BOOL shouldDelete = YES;
for (NSDictionary *jsonDict in jsonData) {
if ([jsonDict objectForKey:@"id"] == idNumber) {
shouldDelete = NO;
}
}
if (shouldDelete) {
// Delete object.
}
}
}
如果 JSON 数组包含大量对象,我认为这将非常低效。
【问题讨论】: