2014-08-28 80 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