识别iCloud coreData更新:良好实践

时间:2014-08-28 00:14:28

标签: ios macos core-data icloud

我有使用iCloud和CoreData(同一容器)的应用程序(iOS和Mac)。每个设备可以创建或更新数据。当设备创建或更新托管对象时,其他设备最终需要执行与托管对象相关的特定操作(与UI无关)。

例如,

  • 设备1处于离线状态,
  • 设备2在线并更改管理对象。
  • 稍后,设备1处于联机状态:它必须标识已创建和更新的托管对象以执行某些操作。

我的问题:我可以依靠通知系统来实现这一目标吗? ( NSPersistentStoreCoordinatorStoresDidChangeNotification NSPersistentStoreDidImportUbiquitousContentChangesNotification

依赖通知意味着我必须确保在数据发生变化时,通知最终会在每台设备上访问我的应用。 特别是,本地商店中的数据同步仅在应用程序运行时执行(因此,如果已经很快注册,通常可以确保通知将到达应用程序)?

或者这种类型的要求是否应该用我自己的机制来实现,以识别商店中的修改? (这会使模型复杂化,因为每个设备都必须知道它已经处理了对特定托管对象的更新)

编辑:看到这句话here

  

首次设置后,来自其他同行的核心数据导入更改持续存储到iCloud,而应用程序正在运行时

这告诉我通知是可靠的。

1 个答案:

答案 0 :(得分: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;
}