NSPersistentContainer 失败且没有错误

NSPersistentContainer fails without error

我突然被 managedObjectContexts 形式的核心数据问题所困扰,三分之二的时间为零:开始或多或少与升级到 Xcode 8. 新的 NSPersistentContainer class 似乎提供了一个机会来解决我的问题并摆脱一些难看的代码。不幸的是,我无法让它发挥作用。

在AppDelegate.h

@property (readonly, strong, nonatomic) NSPersistentContainer *persistentContainer;

在AppDelegate.m中:

@synthesize persistentContainer = _persistentContainer;
- (NSPersistentContainer *)persistentContainer
{
    if (!_persistentContainer) {
        _persistentContainer = [NSPersistentContainer persistentContainerWithName:@"I_WILL_PERSIST"];
        __block BOOL storesWereLoaded = NO;
        [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *psd, NSError *error) {
            if (error) {
                NSLog(@"loadPersistentStoresWithCompletionHandler: persistent container could not load store %@. Error: %@",
                      psd, error.debugDescription);
            } else {
                storesWereLoaded = YES;
            }
        }];
        if (storesWereLoaded) {
            NSLog(@"Stores were loaded");
        } else {
            NSLog(@"Stores were not loaded");
        }
    }
    return _persistentContainer;
}

该应用程序是一个小型测试应用程序,其中一个 arrayController 绑定(在 IB 中)到应用程序 Delegate.persistentContainer.viewContext。 App Delegate 已连接且不为零。 persistentContainer getter 被重复调用,但块内的 NSLog 从不触发并且控制台显示:

Cannot perform operation without a managed object context 2016-09-24 19:34:39.207 I_WILL_PERSIST[5588:180829] ( 0 CoreFoundation
0x00007fff8da994f2 __exceptionPreprocess + 178 1 libobjc.A.dylib
0x00007fff8ed6173c objc_exception_throw + 48 2 CoreFoundation
0x00007fff8db004bd +[NSException raise:format:] + 205 3 AppKit
0x00007fff85d411c4 -[_NSManagedProxy _managedObjectContext] + 66

问题出在我不稳定的块编程技能上吗?是否是签名/权限问题(应用程序不是沙盒,自动代码签名)? Core Data 怎么了?

====编辑==== 升级到 Mac OS 10.12 (Sierra) 后,NSPersistentContainer 失败 并出现 错误:

2016-09-28 20:55:53.256588 osPersist[1936:41151] [error] error:
-addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/user/Library/Application%20Support/osPersist/osPersist.sqlite options:{
    NSInferMappingModelAutomaticallyOption = 1;
    NSMigratePersistentStoresAutomaticallyOption = 1; } ... returned error Error Domain=NSCocoaErrorDomain Code=512 "The file couldn’t be saved." UserInfo={reason=Failed to create file; code = 2} with userInfo dictionary {
    reason = "Failed to create file; code = 2"; } 2016-09-28 20:55:53.256747 osPersist[1936:41151] Unresolved error Error Domain=NSCocoaErrorDomain Code=512 "The file couldn’t be saved." UserInfo={reason=Failed to create file; code = 2}, {
    reason = "Failed to create file; code = 2"; }

数据库创建失败的原因尚不清楚:无论有没有代码签名都会发生。我提交了错误报告并提出了支持请求。

我一升级到 Sierra (MacOS 10.12),NSPersistentContainer 就开始失败 并出现 错误。因此,您可以在 MacOS 10.11 Xcode 8 运行ning 中实现 NSPersistentContainer,您的项目将编译并 运行,但 NSPersistentContainer 不会执行 squat。我已经提交了一份错误报告,我希望 Apple 将预处理器指令添加到 class,但他们似乎不太感兴趣。