2014-05-02 19 views
0

我通过Standford CS193P学习iOS,发现核心数据部分存在问题。我想创建一个应用程序使用核心数据,我创建了一个AppDelegate的类别(我将在didFinishLaunchingWithOptions中创建一个UIManagedDocument),该类别实现一个方法来创建一个UIManagedDocument并将其返回给AppDelegate,以便使用在核心数据中使用UIManagedDocument的标准(或正确)方式

- (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传递给我的视图控制器:我可以打电话self.managedDocument = [自我createUIManagedDocument]得到一个

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

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

这里是我的问题:

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

谢谢你审查我的问题。

回答

1

在课程中,我们被告知要使用通知来做到这一点,他在演讲中以演讲的形式在第十三讲51:20中解释了这一点。

+0

谢谢洛伦佐!我现在使用MagicalRecord https://github.com/magicalpanda/magicalrecord。 – Leon

+0

这是一个答案 - 这个问题涉及一个非常具体的在线课程(无论是提问者还是回答者显然都在考虑),并指出课程材料中提供的解释非常有用。 –

相关问题