我正在尝试在一个项目上使用 Core Data,该项目的代码改编自 iOS 编程:The Big Nerd Ranch Guide(第三版)。打开 SQLite 文件会导致异常,无论阅读多少文档或挖掘搜索引擎都无法帮助我弄清楚它的含义或如何避免它。
相关代码位于数据存储类的 init 方法中,内容如下:
- (id)init
{
self = [super init];
if (self) {
// snip
NSURL *storeURL = [NSURL fileURLWithPath:[self itemArchivePath]];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] init];
NSError *error = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
[NSException raise:@"Couldn't open the SQL file" format:@"Reason: %@", [error localizedDescription]];
}
// snip
}
return self;
}
异常发生在 addPersistentStoreWithType: 行上,因此我们不会在 if block 中处理该异常。这是我被告知的内容:
2013-07-01 14:46:04.647 (app name)[5859:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: NSStoreModelVersionHashes)'
当我在错误行上设置断点时,Xcode 不允许我进入函数调用内部,因此我不确定 NSStoreModelVersionHashes 来自何处或如何避免将其设置为 nil。我可以po storeURL
,它似乎是正确的 URL。重置 iOS 模拟器、为 SQL 文件使用不同的名称或我发现的其他解决方案似乎没有任何帮助。
最佳答案
持久存储协调器需要托管对象模型。它通常是用
创建的NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
其中 managedObjectModel
之前已使用
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"<yourModelName>" withExtension:@"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
查看 Apple 开发人员库中的任何 Core Data 示例代码以获取示例 如何正确设置核心数据堆栈。
关于objective-c - NSPersistentStoreCoordinator addPersistentStoreWithType… 导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17398225/