我正在使用Core Data多年。目前,我想了解有关UIManagedDocument的更多信息。我已经做了几个示例项目来了解它。最后,我很高兴将这种机制转移到真正的项目中。在现有项目中,我目前正在实施核心数据,因此我创建了数据模型(与app同名)。我为一个实体生成了一个类,然后我创建了一个类别,它有一个简单的方法来向数据库添加对象。最后我为UIManagedDocument创建了单例,现在它看起来像这样:
+ (MDManagedDocument *)sharedDocument {
static dispatch_once_t dispatchOncePredicate;
__strong static MDManagedDocument *md = nil;
dispatch_once(&dispatchOncePredicate, ^{
md = [[MDManagedDocument alloc] init];
});
return md;
}
- (id)init {
self = [super init];
if(self) {
[self setManagedDocument:[[UIManagedDocument alloc] initWithFileURL:[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"ThisIsDatabase"]]];
[[self managedDocument] setPersistentStoreOptions:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]];
}
return self;
}
- (void)prepareManagedDocument {
if (![[NSFileManager defaultManager] fileExistsAtPath:[[[self managedDocument] fileURL] path]]) {
[[self managedDocument] saveToURL:[[self managedDocument] fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(@"Managed document was created.");
} else {
NSLog(@"Error occured while creating managed document.");
}
}];
} else if([[self managedDocument] documentState] == UIDocumentStateClosed) {
[[self managedDocument] openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(@"Managed document was opened.");
} else {
NSLog(@"Error occured while opening managed document.");
}
}];
} else if([[self managedDocument] documentState] == UIDocumentStateNormal) {
NSLog(@"Managed document is opened and prepared for editing and/or reading.");
}
}
在我实例化共享实例并调用prepareManagedDocument方法后,它会崩溃并显示以下消息:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString _cfurl]: unrecognized selector sent to instance 0xb3774b0'
有趣的是它只在第一次运行时崩溃,但由于这次崩溃,它不会创建持久存储,因此它将无法写入文档等。我有一个正在运行的项目使用此代码,并且不抛出任何异常,因此它创建了持久存储,我可以写入此文档。
我哪里错了?
提前致谢!
答案 0 :(得分:0)
问题解决了!我有一个扩展NSURL的类别,并且只有一个方法baseURL,删除此类别或重命名方法后一切正常。