2014-08-28 48 views
0

我有使用iCloud和CoreData(相同容器)的應用程序(iOS和Mac)。每個設備都可以創建或更新數據。當設備創建或更新託管對象時,其他設備最終需要執行與託管對象相關的某個操作(與UI無關)。識別iCloud coreData更新:良好做法

因此,例如,

  • 裝置1處於離線狀態,
  • 設備2處於聯機並且改變一個管理對象。
  • 稍後,設備1處於聯機狀態:它必須識別創建和更新的管理對象以執行某些操作。

我的問題:我可以依靠通知系統來實現嗎? (NSPersistentStoreCoordinatorStoresDidChangeNotificationNSPersistentStoreDidImportUbiquitousContentChangesNotification

依託通知意味着我必須肯定的是,通知將最終達到每臺設備上我的應用程序時,數據已經改變。 特別是,本地存儲上的數據同步只在應用程序運行時才執行(因此希望確保通知在應用程序註冊後即可到達應用程序)?

或者應該用我自己的機制來實現這種類型的需求,以識別商店中的修改? (這將在模型複雜化,因爲每個設備必須知道它已處理的更新到特定管理對象)

編輯:鋸這句話here

核心數據出口變化持續到iCloud從首次安裝後的其他同行和而您的應用正在運行

這告訴我,通知是可靠的。

回答

1

根據我的經驗,通知是可靠的。 iCloud的更改只會在應用程序運行時同步。只有在添加了相應的持久存儲後,該同步纔會發生。 (即,您在持久存儲協調器上調用了addPersistentStoreWithType)。

在添加持久性存儲之前,我總是註冊通知(代碼如下所示)。這樣你就可以確定你會收到相關的通知。

// Returns the persistent store coordinator for the application. 
// If the coordinator doesn't already exist, it is created and the application's store added to it. 
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 
    if (_persistentStoreCoordinator != nil) { 
     return _persistentStoreCoordinator; 
    } 

    NSError *error = nil; 
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 

    NSNotificationCenter* notificationCentre = [NSNotificationCenter defaultCenter]; 

    [notificationCentre addObserver:self 
          selector:@selector(CoreData_StoresWillChange:) 
           name:NSPersistentStoreCoordinatorStoresWillChangeNotification 
          object:coordinator]; 
    [notificationCentre addObserver:self 
          selector:@selector(CoreData_StoresDidChange:) 
           name:NSPersistentStoreCoordinatorStoresDidChangeNotification 
          object:coordinator]; 
    [notificationCentre addObserver:self 
          selector:@selector(CoreData_StoreDidImportUbiquitousContentChanges:) 
           name:NSPersistentStoreDidImportUbiquitousContentChangesNotification 
          object:coordinator]; 

    NSMutableDictionary* workingOptions = [self.storeOptions mutableCopy]; 

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.storeURL options:workingOptions error:&error]) { 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return _persistentStoreCoordinator; 
} 
+0

感謝您的回答。關於此聲明的一個問題:_I在添加持久性存儲_之前,始終註冊通知(代碼如下所示)。如果註冊是在同一個隊列執行循環中完成的,那麼在添加商店之後,是否真的會有錯過的通知? – CMont 2014-08-29 03:42:15

+0

我相信在這種情況下,您很可能不會錯過通知。但是,iCloud同步確實在它自己的線程上運行。時間窗口可能非常狹窄,以至於你永遠不會錯過任何通知,但我更喜歡安全地玩。 – 2014-08-29 05:26:41

+0

我似乎完全遵循上述模式。只要一臺設備脫機,一切似乎都可以正常工作。但是,如果兩臺設備都處於脫機狀態,並且將新對象添加到存儲中,則兩臺設備恢復聯機時都不會收到通知,因此不會發生同步。但是,我不確定在給定設備1的脫機狀態或設備2未能接收到它的情況下是否沒有發出任何通知。一旦兩臺設備重新聯機,至少會收到任何內容。感謝您的任何建議! – DoertyDoerk 2015-09-16 10:28:08