我正在尝试使用 UIManagedDocument 在我正在构建的应用程序中设置我的核心数据堆栈。我在 init 方法中有一个对象 DocumentController :
- (id)init
{
if (self = [super init]) {
//custom initialization
NSString *path = [[DMDocumentController documentsDirectory] stringByAppendingPathComponent:@"logDatabase"];
NSURL *documentURL = [NSURL fileURLWithPath:path];
self.managedDocument = [[UIManagedDocument alloc] initWithFileURL:documentURL];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
self.managedDocument.persistentStoreOptions = options;
}
return self;
}
然后我有了这个名为 performWithDocument 的块方法,它使您可以访问块中的文档。块定义如下:
typedef void (^OnDocumentReady) (UIManagedDocument *document);
该方法如下所示:
- (void)performWithDocument:(OnDocumentReady)onDocumentReady
{
void (^OnDocumentDidLoad)(BOOL) = ^(BOOL success) {
onDocumentReady(self.managedDocument);
};
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.managedDocument.fileURL path]]) {
[self.managedDocument saveToURL:self.managedDocument.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:OnDocumentDidLoad];
} else if (self.managedDocument.documentState == UIDocumentStateClosed) {
[self.managedDocument openWithCompletionHandler:OnDocumentDidLoad];
} else if (self.managedDocument.documentState == UIDocumentStateNormal) {
OnDocumentDidLoad(YES);
}
}
无论如何,每当我尝试插入一个新实体时,我的应用程序在事后几秒钟(当它尝试保存时)崩溃并且我在标题中收到错误消息。当我认为 UIManagedDocument 为我处理了核心数据堆栈内容时,我不确定如何解决这个问题。有没有人有任何指针?