NSIncrementalStore - 使用本地和远程数据

wcz*_*ski 5 iphone macos core-data ios nspersistentstore

我已经阅读了一些文章NSIncrementalStore,我仍然对整个概念感到困惑.在这篇文章中我们可以读到:

从本质上讲,您现在可以创建一个自定义子类NSPersistentStore,这样您NSFetchRequest就可以运行一个定义的方法,而不是命中本地SQLite数据库,该方法可以执行任意操作以返回结果(例如发出网络请求).

到目前为止,我认为NSIncrementalStore是访问远程数据并在本地保存/缓存的完美解决方案.现在,我推断它只是一种用于访问远程数据的解决方案.

如果我是对的,我会感谢任何关于某些解决方案的建议.如果我错了,魔法在哪里以及如何实现它?NSIncrementalStore上的每篇文章/文章/教程都显示了从服务器提取数据的难易程度,但他们都没有提供有关缓存离线查看内容的单一线索.

回答一下,让我们考虑一个常见的场景,即应用程序应该从Internet下载一些数据,显示并保存在本地,以便用户可以离线使用该应用程序.

此外,我不承诺使用NSIncrementalStore或其他东西.我只是在寻找最好的解决方案,这个类被这个领域的一些最好的专家描述为一个.

Ale*_*aev 0

我也困惑了大约四五个小时:) 所以。您继承的 NSPercientStore 类是远程数据存储的“表示”。

因此,为了访问远程数据并在本地保存/缓存它,您需要执行以下操作

1)创建 NSPersistentStore 的子类并设置它。

像那样:

YOURIncrementalStore *incrementalStore = [coordinator addPersistentStoreWithType:[YOURIncrementalStore type] configuration:nil URL:nil options:nil error:&error];

其中 coordinator 你的主要 NSPersistentStoreCoordinator

2)然后,您需要其他 NSPersistentStoreCoordinator,它将“协调本地表示(incrementalStore)和外部存储的上下文”并向其提供本地存储表示(如 SQLite DB URL):

[incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]

但不要忘记,您的新持久存储必须知道您以前的所有本地状态。所以选项字典将是:

NSDictionary *options = @{ NSInferMappingModelAutomaticallyOption : @YES, NSMigratePersistentStoresAutomaticallyOption:@YES }

所以,恕我直言,我这样理解所有内部工作:

您从外部 API 请求一些数据。解析它,然后保存到 backingPersistentStoreCoordinator 的上下文中,然后合并到主上下文中。所以所有上下文的状态都是相等的。

前面的所有文本均基于使用 AFIncrementalStore 解决方法。

我用 MagicalRecord 实现 AFIncrementalStore 的代码:

  - (void)addMRAndAFIS {
    [MagicalRecord setupCoreDataStack];

    NSURL *storeURL = [NSPersistentStore urlForStoreName:[MagicalRecord defaultStoreName]];
    NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator defaultStoreCoordinator];
    NSError *error = nil;
    NSArray *arr = coordinator.persistentStores;
    AFIncrementalStore *incrementalStore = (AFIncrementalStore*)[coordinator addPersistentStoreWithType:[PTIncrementalStore type] configuration:nil URL:nil options:nil error:&error];

    NSDictionary *options = @{ NSInferMappingModelAutomaticallyOption : @YES,
                         NSMigratePersistentStoresAutomaticallyOption:@YES };
    arr = coordinator.persistentStores;
    if (![incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果我们需要讨论最简单的方法,您只需要子类 NSIncrementalStore,正确设置它(就像我写的那样),解析数据,然后创建一些上下文,将日期保存到其中,然后保存它并合并到父上下文。

所以你将有 2 个 Store 和 2 个上下文,以及 1 个 StoreCoordinator。

如果我在某个地方犯了错误,请参考它。

另外,请尝试: https: //gist.github.com/stevederico/5316737