问题
I am running into a weird problem. I am sure that I did something to a file somewhere else in my code and it didn't close properly or something, but now it is in a state where it reports as being closed, but when I call OpenWithCompletionHandler it never returns. See below:
//if the file is closed, open it and then set up the controller
if (file.documentState == UIDocumentStateClosed){
//---- this code executes
[file openWithCompletionHandler:^(BOOL success){
// ---- this code NEVER executes
}];
}
Any ideas?
回答1:
See Bug in iPhone Simulator 5.1 with Xcode 4.5 using UIManagedDocument.
My solution was along the same lines as those reported, but I had to lower the Deployment Target of my app to iOS 5.0 so that "iPhone 5.0 Simulator" was available as a run target. I have only seen this issue trying to use the iPhone 5.1 Simulator with XCode 4.5.2, both the 5.0 and 6.0 simulators work.
回答2:
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;
}
}
来源:https://stackoverflow.com/questions/12439528/uimanageddocument-openwithcompletionhandler-never-returns