此前,我有一個使用核心數據的應用程序。我使用相同的商店URL來初始化NSManagedObjectModel並創建NSPersistentStoreCoordinator。但是,在新應用程序中,我嘗試使用相同的方式,無法創建模型。所以我必須使用模型url(我在這個論壇中發現它)能夠創建NSManagedObjectModel。什麼是問題?核心數據模型路徑vs商店路徑
下面是從舊的應用程序:
- (NSString *)storeName
{
return @"ABC.storedata";
}
- (NSURL *)storeUrl
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:self.storeName];
return storeURL;
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel == nil) {
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[self storeUrl]];
}
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeUrl] options:nil error:&error]) {
abort();
}
return _persistentStoreCoordinator;
}
這裏是新的應用程序:
- (NSString *)storeName
{
return @"DEF.sqlite";
}
- (NSURL *)storeUrl
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:self.storeName];
return storeURL;
}
- (NSURL *)modelUrl
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DEF" withExtension:@"momd"];
return modelURL;
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel == nil) {
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[self modelUrl]];
}
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeUrl] options:nil error:&error]) {
abort();
}
return _persistentStoreCoordinator;
}
好的。你是對的。我得到了爲什麼舊應用程序工作的原因。舊應用程序使用mergedModelFromBundles,而不是initWithContentsOfURL。 – angelokh