私も約4、5時間混乱していました:)だから。NSPersistentStore の継承されたクラスは、リモート データ ストレージの「表現」です。
したがって、リモート データにアクセスしてローカルに保存/キャッシュするには、次の手順を実行する必要があります。
1) NSPersistentStore のサブクラスを作成し、セットアップします。
そのように:
YOURIncrementalStore *incrementalStore = [coordinator addPersistentStoreWithType:[YOURIncrementalStore type] configuration:nil URL:nil options:nil error:&error];
どこでコーディネーターがメインの NSPersistentStoreCoordinator
2)次に、「外部ストレージのローカル表現(incrementalStore)とコンテキストを調整」し、ローカルストレージ表現(SQLite DB URLなど)を提供する他のNSPersistentStoreCoordinatorが必要です。
[incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]
ただし、新しい永続ストアは以前のローカル状態をすべて認識している必要があることを忘れないでください。したがって、オプション 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 つの Store と 2 つのコンテキスト、および 1 つの StoreCoordinator があります。
どこか間違っていたら参考にしてください。
また、試してみてください:https://gist.github.com/stevederico/5316737