Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPersistentStoreCoordinator with two types of persistent stores?

Tags:

ios

core-data

In an iOS app, I would like to use an NSPersistentStoreCoordinator with both an NSIncrementalStore subclass, for fetching data from a REST API, but also with an SQLite store, to save to disk. If I add both types of persistent stores to my coordinator, however, calling save: on my managed object context has no effect. If I only add the one persistent store, not of the type for my NSIcrementalStore subclass, then the save works as intended.

Is there any way to achieve this functionality?

like image 691
Jordan Kay Avatar asked Sep 07 '12 16:09

Jordan Kay


1 Answers

The best solution in my experience is to have multiple managed object contexts, each having its own model.

However, there is a way to accomplish what you want:

// create the store coordinator
NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] init];
// create the first store
NSPersistentStore *firstStore = [storeCoordinator addPersistentStoreWithType: NSIncrementalStore configuration:nil URL:urlToFirstStore options:optionsForFirstStore error:&error];
// now create the second one
NSPersistentStore *secondStore = [storeCoordinator addPersistentStoreWithType:NSSQLiteStore configuration:nil URL:urlToSecondStore options:optionsForSecondStore error:&error];

// Now you have two stores and one context
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:storeCoordinator];

// and you can assign your entities to different stores like this
NSManagedObject *someObject = [[NSManagedObject alloc] initWithEntity:someEntity insertIntoManagedObjectContext:context];
// here the relevant part
[context assignObject:someObject toPersistentStore:firstStore]; // or secondStore ..

You should also check these links to get a better idea about how Core Data works:

Core Data Programming Guide - Persistent Store Coordinator

SO: Two persistent stores for one managed object context - possible?

SO: Can two managed object context share one single persistent store coordinator?

Also check the comment by TechZen in the second link about configurations and read about it in here:

Core Data Programming Guide - Configurations

and here is a nice tutorial to manage two object contexts:

Multiple Managed Object Contexts with Core Data

like image 55
iska Avatar answered Oct 13 '22 07:10

iska