此处可能重复。
您可以拥有任意数量的数据模型,只要您为每个模型创建不同的托管对象上下文并正确管理它们。
- (NSURL *)applicationDocumentsDirectoryForCoreData
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//第一个数据模型
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();
}
//第二个模型。
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();
}
在为您想要的商店取出 MOC 时:
//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];
}
两个商店之间的选择。
-(NSPersistentStoreCoordinator *)selectStore
{
if(someCondtion? return persistentStoreCoordinator1: persistentStoreCoordinator2;
}