我开始使用 Core Data 进行 iPhone 开发。我首先创建了一个非常简单的实体(称为评估),它只有一个字符串属性(称为评估主题)。我有以下用于插入新字符串的代码:
- (void)insertNewObject {
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
[newManagedObject setValue:@"My Repeating String" forKey:@"evaluationTopic"];
// Save the context.
NSError *error;
if (![context save:&error]) {
// Handle the error...
}
[self.tableView reloadData];
}
这工作得非常好,通过按下 + 按钮,一个新的“我的重复字符串”将被添加到表视图中并保存在持久存储中。
然后我在 Xcode 中按下“设计 - > 添加模型版本”。我向现有实体添加了三个实体,并向现有的“评估”实体添加了新属性。然后,我通过按“文件 -> 新文件 -> 托管对象类”从实体中创建了新文件,并为我的四个实体创建了一个新的 .h 和 .m 文件,包括带有 Evaluation.h 和 Evaluation 的“Evaluation”实体.m。现在我通过设置“设计 -> 数据模型 -> 设置当前版本”来更改模型版本。完成所有这些后,我更改了我的 insertMethod:
- (void)insertNewObject {
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
Evaluation *evaluation = (Evaluation *) [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
[evaluation setValue:@"My even new string" forKey:@"evaluationSpeechTopic"];
// Save the context.
NSError *error;
if (![context save:&error]) {
// Handle the error...
}
[self.tableView reloadData];
}
这虽然行不通!每次我想添加一行时,模拟器都会崩溃,我得到以下信息:
"NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'"
在更改数据模型上的任何内容后,我在知道创建新版本之前就遇到了这个错误,但为什么这仍然会出现?我是否需要进行任何映射(即使我只是添加了以前不存在的实体和属性?)。在 Apple Dev 教程中,这听起来很简单,但我一直在努力解决这个问题,在更改模型版本后从未工作过。