我正在制作一个基于某些属性(例如名称、颜色、重量等)显示生物体的应用程序,但这些属性要到运行时才能知道。这就是我以编程方式创建 NSManagedObjectModel 的原因。似乎我能够正确初始化模型,因为我使用 NSLog 语句来显示有机体实体的属性。但是当我调用该方法时:
[orgPersistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]
它返回 NO 并且我在持久存储协调器方法中收到错误消息:
“无法添加持久存储:操作无法完成。(Cocoa 错误 256。)”
我试过打开这些选项,但我仍然遇到同样的错误:
NSString * const NSMigratePersistentStoresAutomaticallyOption;
NSString * const NSInferMappingModelAutomaticallyOption;
这是完整的代码:
- (NSPersistentStoreCoordinator *)orgPersistentStoreCoordinator {
if (orgPersistentStoreCoordinator != nil) {
return orgPersistentStoreCoordinator;
}
NSURL *storUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:@"organisms.sqlite"]];
NSError *error = nil;
orgPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self orgManagedObjectModel]];
NSLog(@"Entities: %@",[[self orgManagedObjectModel] entities]);
if (![orgPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
NSLog(@"Could not add persistent store:%@",[error localizedDescription]);
}
return orgPersistentStoreCoordinator;
}
这是我如何以编程方式创建 ManagedObjectModel 的片段。
+ (NSManagedObjectModel *) orgManagedObjectModel
{
FieldGuide *f = [FieldGuide sharedFieldGuide];
NSManagedObjectModel *orgModel = [[NSManagedObjectModel alloc]init];
NSEntityDescription *organismEntity = [[NSEntityDescription alloc]init];
[organismEntity setName:@"OrganismCoreData"];
[organismEntity setManagedObjectClassName:@"OrganismCoreData"];
[orgModel setEntities:[NSArray arrayWithObject:organismEntity]];
NSMutableArray *orgEntityProperties = [[NSMutableArray alloc]init];
// 1. Name attributes
for (NameParameter *n in f.nameAttributes)
{
NSAttributeDescription *nameAttr = [[NSAttributeDescription alloc]init];
[nameAttr setName:n.name];
[nameAttr setAttributeType:NSStringAttributeType];
[orgEntityProperties addObject:nameAttr];
}
[organismEntity setProperties:orgEntityProperties];
return orgModel;
}
最后,当我尝试插入一些生物体并通过 NSManagedObjectContext 保存时,应用程序终止并在日志中显示:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
任何帮助或指导将不胜感激,谢谢!
编辑:是的,我已经尝试从模拟器中删除应用程序,清理目标,并通过finder从文档文件夹中删除organism.sqlite。
编辑#2:我忘了添加 addPersistentStore 方法也返回另一个错误:
2012-04-30 14:13:46.109 biodex[7510:14803] CoreData: error: (1) I/O error for database at /Users/junryandelacruz/Library/Application Support/iPhone Simulator/5.1/Applications/ACE957AF-2FC0-4EAF-B226-5019F70FAB90/Documents/organisms.sqlite. SQLite error code:1, 'near "OR": syntax error'