我已经阅读了几篇关于 NSIncrementalStore
的文章,但我仍然对整个概念感到困惑。在这个post我们可以读到:
Essentially you can now create a custom subclass of
NSPersistentStore
, so that instead of yourNSFetchRequest
hitting a local SQLite database, it runs a method you define that can do something arbitrary to return results (like make a network request).
到目前为止,我认为 NSIncrementalStore 是访问远程数据并在本地保存/缓存它的完美解决方案。现在,我推断这是一个仅用于访问远程数据的解决方案。
如果我是对的,我将感谢任何关于解决方法的建议。 如果我错了,魔法在哪里以及如何实现呢? NSIncrementalStore 上的每一篇文章/文章/教程都展示了从服务器中提取数据是多么容易,但没有一个给出关于缓存内容以供离线查看的线索。
回答,让我们考虑一个常见的场景,一个应用程序应该从互联网上下载一些数据,显示它并保存在本地,以便用户可以离线使用该应用程序。
此外,我不 promise 使用 NSIncrementalStore 或其他东西。我只是在寻找最好的解决方案,并且这个类(class)被该领域的一些最优秀的专家描述为一个类(class)。
最佳答案
我也困惑了大约 4 或 5 个小时 :) 所以。 您继承的 NSPersistentStore 类是远程数据存储的“代表”。
因此,对于访问远程数据并在本地保存/缓存,您需要执行以下操作
1) 创建 NSPersistentStore 的子类并设置它。
像那样:
YOURIncrementalStore *incrementalStore = [coordinator addPersistentStoreWithType:[YOURIncrementalStore type] configuration:nil URL:nil options:nil 错误:&error];
协调器是你的主要 NSPersistentStoreCoordinator
2) 然后,您需要其他 NSPersistentStoreCoordinator,它将“协调本地表示(incrementalStore)和外部存储的上下文”并向其提供您的本地存储表示(如 SQLite DB URL):
[incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 配置: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();
}
}
如果我们需要讨论最简单的方法,您只需要子类 NSIncrementalStore,正确设置它(就像我写的那样),解析数据,然后创建一些上下文,将日期保存到它,然后保存并合并到父上下文。
因此您将拥有 2 个 Stores 和 2 个上下文,以及 1 个 StoreCoordinator。
如有错误,请指正。
关于iphone - NSIncrementalStore - 使用本地和远程数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813652/