我使用一个名为THSettings的实体正确运行Core Data(加载,保存)。
但是,我想创建一个名为THDetails的另一个不相关的Core Data实体。
当我在同一个xcdatamodeld文件中创建另一个实体时,它在运行应用程序时给出了这个错误:“用于打开商店的模型与用于创建商店的模型不兼容”。
所以我删除了该实体并为新实体创建了另一个xcdatamodeld文件,现在它给出了这个错误: “ * 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'NSFetchRequest找不到实体名称的NSEntityDescription'THDetails''”
任何人都可以告诉我为什么这不起作用?我应该能够保存多个不相关的实体......
以下是加载THDetails的代码:
-(NSMutableArray *)loadSavedNotes {
THAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"THDetails"];
NSMutableArray *detailsList = [[moc executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(@"%d", [detailsList count]);
return detailsList;
}
以下是加载THSettings的代码:
THAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"THSettings"];
NSMutableArray *settingsList = [[moc executeFetchRequest:fetchRequest error:nil] mutableCopy];
// ... process it
答案 0 :(得分:1)
您需要定义一个定义 all 实体的模型。如果您添加额外的 实体到模型,你有两个选择:
答案 1 :(得分:1)
问题在于,当您更改模型时,持久性存储(即sqlite数据库)将与更改的模型不兼容。 有几种方法可以处理此类错误,例如执行轻量级迁移。
最简单的方法是简单地重新创建持久存储:
NSError *error = nil;
NSURL *storeURL = ...;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
// if storeCoordinator can't open at storeURL for some reason
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error])
{
// if there is a database - it means it's the problem - delete it
if ([[NSFileManager defaultManager] fileExistsAtPath:storeURL.path])
{
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
// if storeCoordinator still can't open a database, means some other error
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Database structure has changed. All information had been erased"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil;
[alertView show];
}
}