UIManagedDocument OpenWithCompletionHandler never returns

佐手、 提交于 2019-12-06 04:03:58
Joe

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.

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!