OpenWithCompletionHandler

OpenWithCompletionHandler

本文介绍了UIManagedDocument OpenWithCompletionHandler永不返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个奇怪的问题.我确定我对代码中的其他位置的文件做了某些操作,但未正确关闭或执行某些操作,但是现在它处于报告为已关闭的状态,但是当我调用OpenWithCompletionHandler时,它永远不会返回.见下文:

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
        }];
    }

有什么想法吗?

推荐答案

我遇到了同样的问题.

您是否要在viewDidLoad中打开文档?

Are you trying to open the document inside viewDidLoad?

尝试将代码移至另一种方法.它为我解决了这个问题.

Try moving the code to another method. It solved the problem for me.

在ViewController.h

in ViewController.h

@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic,strong) UIManagedDocument *document;

在ViewController.m

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;
    }
}

这篇关于UIManagedDocument OpenWithCompletionHandler永不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 18:06