我正在创建一个基于某些属性显示生物的应用程序,例如名称,颜色,重量等,但这些属性在运行时才会知道。这就是我以编程方式创建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从文档文件夹中删除organisms.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'
答案 0 :(得分:1)
您的storeURL
看起来有误。这是“未知文件读取错误”,通常与文件路径有关。
NSFileReadUnknownError = 256,
第二个错误肯定与添加持久存储无关。检查代码中的“OR”谓词。