objective-c - NSPersistentStoreCoordinator addPersistentStoreWithType… 导致异常

标签 objective-c cocoa core-data

我正在尝试在一个项目上使用 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/

相关文章:

iphone - iPhone SDK 的文件错误

objective-c - 在 Interface Builder 中使 NSButton 跟随 ScrollView

ios - mergeChangesFromContextDidSaveNotification 后的 KVO 通知

cocoa 绑定(bind)和核心情节

javascript - 从 Javascript 调用 iOS Webview 委托(delegate)未触发

objective-c - 应用程序在 : openDocumentWithContentsOfURL:display:error: 处停止执行

objective-c - indentationLevel 属性似乎没有做任何事情?

iphone - 正确存储核心数据中一对多关系的数据

ios - Restkit 本地数据映射操作似乎没有保存到磁盘

ios - 以编程方式将 NSLayoutAttributeLeading Space 设置为 Superview 并带有一些警告