2013-05-13 32 views
2

我有一個應用程序,我已經與iCloud整合了核心數據。我在視圖控制器中有以下通知。使用iCloud更新UITableView更新

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreCoordinatorStoresDidChangeNotification object:coreDataController.psc]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coreDataController.psc]; 

視圖控制器包含裝載有使用NSFetchedResultsController核心數據UITableView。我不確定要在以下方法中放置什麼(由上述通知調用)來刷新表格。我嘗試重新加載表格,並重新提交數據,但無濟於事。我知道iCloud正在做它的工作,因爲如果我完全重新加載視圖控制器,更改後的數據顯示。

- (void)reloadFetchedResults:(NSNotification*)note { 
    NSLog(@"Underlying data changed ... refreshing!"); 

    //_fetchedResultsController=nil; 
    //[self fetchedResultsController]; 

    [theTableView reloadData]; 


} 

任何幫助將不勝感激,謝謝!

+0

你居然刷新數據源?或者只是重新加載表? – Peres 2013-05-13 09:07:56

+0

嗯,我已經嘗試調用'NSFetchResultsController'委託方法來重新獲取數據,(註釋掉了一點),但這也沒有奏效。 – 2013-05-13 09:13:06

回答

4

您是否需要獲取另一組數據,或者您是否希望看到對相同結果集的更改?如果前者,將其撕下並用新的謂詞重新構建,獲取等等,然後執行獲取。

如果是後者,您需要將您的更改與您的moc合併。當您註冊通知時,請將其設置爲:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentContentsImportedChanges:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:self.managedObjectContext.persistentStoreCoordinator]; 


- (void) documentContentsImportedChanges:(NSNotification*)notification 
{ 
    // Received updates from iCloud 
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification]; 
} 
+0

謝謝!它是後者。 – 2013-05-15 08:52:09

+0

5豎起大拇指!真棒的答案,和一個奇妙的問題。爲我工作,謝謝你們! – 2014-03-24 16:28:06

2

我同意Jason的回答。但是,您應該確保您在正確的線程中執行更新。

[[NSNotificationCenter defaultCenter] addObserver:self 
       selector:@selector(persistentStoreDidImportUbiquitousContentChanges:) 
        name:NSPersistentStoreDidImportUbiquitousContentChangesNotification 
       object:_persistentStoreCoordinator]; 

- (void)persistentStoreDidImportUbiquitousContentChanges:(NSNotification*)note 
{ 
    NSManagedObjectContext *moc = self.managedObjectContext; 
    [moc performBlock:^{ 
     [moc mergeChangesFromContextDidSaveNotification:note]; 

    }]; 
} 

更新MOC的這種方法可以確保其在同一個線程上下文中完成,所以你沒有任何崩潰;)