繁体   English   中英

在核心数据中使用UIManagedDocument的标准(或正确)方法是什么

[英]What is the standard(or correct) way to use UIManagedDocument in core data

我正在通过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吗?

感谢您审查我的问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM