NSIncrementalStore - 使用本地和远程数据

时间:2013-07-23 14:51:44

标签: iphone ios macos core-data nspersistentstore

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

  

基本上,您现在可以创建NSPersistentStore的自定义子类,   这样代替你的NSFetchRequest命中本地SQLite   数据库,它运行一个你定义的方法,可以做任意的事情   返回结果(如发出网络请求)。

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

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

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

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

1 个答案:

答案 0 :(得分:0)

我也困惑了大约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 URL):

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

但不要忘记,您的新持久商店必须知道您所有之前的本地状态。所以选项dict将是:

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

所以,imho,我这样理解所有内部工作:

您从外部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个商店和2个上下文,以及1个StoreCoordinator。

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

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