我正在尝试使用UIManagedDocument在我正在构建的应用程序中设置核心数据堆栈。我有一个对象DocumentController在init方法中有这个:
- (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的块方法,它允许您访问块中的Document。块的定义如下:
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为我处理核心数据堆栈时,我不确定如何纠正这个问题。有人有任何指针吗?