0

我正在通过 Standford CS193P 学习 iOS,我在核心数据部分遇到了问题。

我正在尝试使用核心数据构建应用程序,我为 AppDelegate 创建了一个类别(我将在 didFinishLaunchingWithOptions 中创建一个 UIManagedDocument),该类别实现了一种方法来创建 UIManagedDocument 并将其返回给 AppDelegate,以便我可以调用 self .managedDocument = [self createUIManagedDocument] 得到一个:

- (UIManagedDocument *)createUIManagedDocument
{

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *url = [documentsDirectory URLByAppendingPathComponent:APP_NAME];
    UIManagedDocument *managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];

    if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
        // If the file exists, open it
        NSLog(@"File exists, not opening...");
        [managedDocument openWithCompletionHandler:^(BOOL success) {
            NSLog(@"File opened.");
        }];
    } else {
        // If the file not exists, create it
        NSLog(@"File not exists, now creating...");
        [managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            // If the file create succesfully, open it
            [managedDocument openWithCompletionHandler:^(BOOL success) {
                NSLog(@"File opened.");
            }];
        }];
    }
    return managedDocument;
}

创建 UIManagedDocument 后,我​​尝试使用以下方法将此 UIManagedDocument 传递给我的视图控制器:

RootViewController *rootViewController = (RootViewController *)self.window.rootViewController;
rootViewController.managedDocument = self.managedDocument;

问题发生了,我无法在我的视图控制器中打开 UIManagedDocument。搜了一整天,得到了答案:我在异步的时候尝试同时打开两次,处理IO请求需要时间。有一些方法,其中大多数使用 Singleton。

这是我的问题:

  1. 我可以使用上面的方法来做到这一点吗?
  2. 如果不是,在我的应用程序周围创建和传递此 UIManagedDocument 的标准(或正确)方法是什么?
  3. 我应该将此 UIManagedDocument 中的 NSManagedObjectContext 传递给我的视图控制器,而不是传递 UIManagedDocument 吗?

感谢您审查我的问题。

4

1 回答 1

1

在课程中,我们被告知使用通知来执行此操作,他在第 13 课 51:20 的演示中对此进行了解释。

于 2014-05-07T15:36:14.087 回答