我遇到了同样的问题。
您是否尝试在 viewDidLoad 中打开文档?
尝试将代码移动到另一种方法。它为我解决了这个问题。
在 ViewController.h
@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic,strong) UIManagedDocument *document;
在 ViewController.m
@synthesize managedObjectContext = _managedObjectContext;
@synthesize document = _document;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do not try to open the document here
// Call another method instead :D
if (!_managedObjectContext) {
[self createContext];
}
}
- (void)createContext
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *url = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"Database"];
self.document = [[UIManagedDocument alloc] initWithFileURL:url];
// FILE DOES NOT EXIST - Let's create a new one
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
[self.document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = self.document.managedObjectContext;
} else {
NSLog(@"ERROR: Cannot create new document");
}
}];
// FILE IS CLOSED - Let's open it
} else if (self.document.documentState == UIDocumentStateClosed) {
[self.document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = self.document.managedObjectContext;
} else {
NSLog(@"File is closed and it wont open!");
}
}];
// FILE EXISTS AND IS OPENED - Yay!
} else {
self.managedObjectContext = self.document.managedObjectContext;
}
}