【问题标题】:What is the most efficient way to sync Core Data with JSON API将核心数据与 JSON API 同步的最有效方法是什么
【发布时间】: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 数组包含大量对象,我认为这将非常低效。

【问题讨论】:

    标签: iphone ios json core-data


    【解决方案1】:

    这可能没问题,但我认为您应该应用 Apple 文档中建议的 Find-or-Create 模式。请参阅此处以获取深入的解释 Efficiently Importing Data(特别是请参阅高效实施 Find-or-Create)。

    总体思路很简单。有两个对象数组(一个是从 Core Data 中检索的,一个是从服务中检索的),它们是有序的(分别由 apiIDid 排序)。

    显然如果有很多数据,我真的建议在后台执行操作。请记住,每个线程都需要依赖其NSManagedObjectContext。否则,请利用 iOS 5 API 提供的新队列机制。

    为了完整起见,我还建议阅读 RayWenderlich 教程How To Synchronize Core Data with a Web Service 第 1 和 2 部分。非常有趣。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2011-08-17
      • 2020-04-26
      • 2017-01-08
      • 2012-05-16
      • 2011-08-08
      • 1970-01-01
      相关资源
      最近更新 更多