5

我已经阅读了几篇有关的文章NSIncrementalStore,但我仍然对整个概念感到困惑。在这篇文章中,我们可以读到:

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

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

如果我是对的,我将感谢任何关于解决方法的建议。如果我错了,魔法在哪里以及如何实施?NSIncrementalStore 上的每篇文章/文章/教程都展示了从服务器提取数据是多么容易,但没有一个给出关于缓存内容以供离线查看的单一线索。

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

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

4

1 回答 1

0

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

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

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

像那样:

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

where coordinator 你的主要 NSPersistentStoreCoordinator

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

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

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

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

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

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

于 2013-07-26T10:49:46.393 回答