I am working on an ipad app where I am dealing with core data.
The data managed by the app can be categorised into two categories.
so in the scenario, I got a thought to have two model file in my project and two corresponding sqlite files. And synching one sqlite file to order to achieve synching.
Please suggest, if my approach is right and feasible. If not, then please suggest other solutions.
Please try to understand the question. Here I am talking about of two sqlite files having different structure from each other. Means ".xcdatamodel" model files
Possible duplicate here.
You can have any number of data models, provided you create different managed object contexts for each and manage them properly.
- (NSURL *)applicationDocumentsDirectoryForCoreData
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//first data model
NSURL *modelURL1 = [[NSBundle mainBundle] URLForResource:@"1_model" withExtension:@"momd"];
NSURL *storeURL1 = [[self applicationDocumentsDirectoryForCoreData] URLByAppendingPathComponent:@"1_model.sqlite"];
NSError *error = nil;
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL1];
persistentStoreCoordinator1 = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel];
if (![persistentStoreCoordinator1 addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL1 options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
//second model.
NSURL *modelURL2 = [[NSBundle mainBundle] URLForResource:@"2_model" withExtension:@"momd"];
NSURL *storeURL2 = [[self applicationDocumentsDirectoryForCoreData] URLByAppendingPathComponent:@"2_model.sqlite"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL2];
NSError *error = nil;
persistentStoreCoordinator2 = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if (![persistentStoreCoordinator2 addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL2 options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
And while taking out the MOC for the store you want:
//select your store - do that in selectStore or a function like that.
NSPersistentStoreCoordinator *coordinator = [self selectStore];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
Selection between two stores.
-(NSPersistentStoreCoordinator *)selectStore
{
if(someCondtion? return persistentStoreCoordinator1: persistentStoreCoordinator2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With