1

我有一个关于 CoreData 的问题,其上下文来自 UIManagedDocument。

在下面的这个片段中,它从不记录“打开文档时出错”,但总是“文档仍然关闭” - 为什么我不能打开文档?请问有什么想法吗?

-(void)openDocument
{
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory     inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"Default Date Database"];

    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];

    if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
    {
        [document openWithCompletionHandler:^(BOOL success){
            if (!success) {
            // Handle the error.
            NSLog(@"Error opening the document");
           }
        }];
    }
    else
    {
        [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
        if (!success) {
            // Handle the error.
            NSLog(@"Error saving the file");
            }
        }];
    }

    self.theDocument = document;


    if (self.theDocument.documentState == UIDocumentStateClosed)
    {
        NSLog(@"Document still closed!");
    }

}
4

1 回答 1

2

openWithCompletionHandler是一种异步方法。它只启动一个后台线程来打开和读取文档。当您检查时documentState,这个后台线程可能还没有完成,因此状态仍然是“关闭”。

openWithCompletionHandler当文档已打开(或失败时)时执行 completionHandler 块。

于 2012-08-22T22:32:17.523 回答