I was having the same problem.
Are you trying to open the document inside viewDidLoad?
Try moving the code to another method. It solved the problem for me.
in ViewController.h
@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic,strong) UIManagedDocument *document;
in 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;
}
}