我读过一些关于NSIncrementalStore的文章,我仍然对整个概念感到困惑。在这个post中,我们可以读到:
实际上,您现在可以创建
NSPersistentStore的自定义子类,这样您的NSFetchRequest就可以不访问本地SQLite数据库,而是运行您定义的方法,该方法可以执行任意操作来返回结果(比如发出网络请求)。
到目前为止,我认为NSIncrementalStore是,是访问远程数据和保存/缓存本地的完美解决方案。现在,我推断这是一个只用于访问远程数据的解决方案。
如果我是对的,我会感谢任何关于工作的建议。如果我错了,魔法在哪里?如何实现?NSIncrementalStore上的每一篇文章/教程都展示了从服务器上提取数据是多么容易,但它们都没有给出一条关于缓存东西以供脱机查看的线索。
在回答这个问题时,让我们考虑一个常见的场景:应用程序应该从Internet下载一些数据,显示数据并保存在本地,这样用户就可以脱机使用应用程序了。
此外,我也不承诺使用NSIncrementalStore或其他什么。我只是在寻找最好的解决方案,这门课被这个领域的一些最优秀的专家描述为一个人。
发布于 2013-07-26 10:49:46
我也困惑了大约4到5个小时:)所以。继承的NSPersistentStore类是远程数据存储的“表示”。
因此,对于访问远程数据并在本地保存/缓存数据的,需要执行以下操作
1)创建NSPersistentStore的子类并进行设置。
就像这样:
YOURIncrementalStore *incrementalStore = [coordinator addPersistentStoreWithType:[YOURIncrementalStore type] configuration:nil URL:nil options:nil error:&error];
哪里协调器您的主要NSPersistentStoreCoordinator
2)然后,您需要其他NSPersistentStoreCoordinator,它将“协调本地表示(IncrementalStore)和外部存储的上下文”,并向它提供本地存储代表(如SQLite DB ):
[incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]
但是不要忘记,您的新持久存储必须知道所有的以前的本地状态。因此,备选方案将是:
NSDictionary *options = @{ NSInferMappingModelAutomaticallyOption : @YES, NSMigratePersistentStoresAutomaticallyOption:@YES }
所以,伊霍,我是这样理解所有内部工作的:
您从外部API请求一些数据。解析它,然后保存到backingPersistentStoreCoordinator的上下文,然后合并到主上下文。所以所有上下文的状态都是相等的。
前面的所有文本都是基于使用AFIncrementalStore解决方案的工作。
我用AFIncrementalStore实现MagicalRecord的代码:
- (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个存储库和2个上下文,以及1个StoreCoordinator。
如果我在什么地方弄错了,请参考。
https://stackoverflow.com/questions/17813652
复制相似问题