2014-05-02 18 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

這是一個答案 - 這個問題涉及一個非常具體的在線課程(無論是提問者還是回答者顯然都在考慮),並指出課程材料中提供的解釋非常有用。 –

相關問題