iCloud not syncing properly for Core Data (iOS7)

后端 未结 1 804
情歌与酒
情歌与酒 2021-02-11 01:02

I\'m attempting to sync Core Data among devices using iCloud (using the new iOS7 method). I\'m still seeing issues with the syncing when testing with the simulators. Sometimes d

相关标签:
1条回答
  • 2021-02-11 01:08

    Here is how I do it. It might be an easy way to simplify and unclutter your code.

    self.managedObjectContext = [[NSManagedObjectContext alloc] 
                                initWithConcurrencyType:NSMainQueueConcurrencyType];
    self.managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
    self.managedObjectContext.persistentStoreCoordinator = 
                                [[NSPersistentStoreCoordinator alloc] 
                                initWithManagedObjectModel:self.managedObjectModel];
    
    [self.managedObjectContext.persistentStoreCoordinator 
        addPersistentStoreWithType:NSSQLiteStoreType
        configuration:nil
        URL:self.storeURL
        options:@{ NSPersistentStoreUbiquitousContentNameKey : @"iCloudStore" }
        error:&error];
    

    The only iCloud bit is the options parameter. (I removed other options for clarity.) The store URL is just [documentsDirectory URLByAppendingPathComponent:@"Store.sqlite"].

    I am also listening to these:

    NSPersistentStoreDidImportUbiquitousContentChangesNotification
    NSPersistentStoreCoordinatorStoresWillChangeNotification
    NSPersistentStoreCoordinatorStoresDidChangeNotification
    

    In the first one, I call

    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:note];
    

    and post another notification to update the UI; in the second one, I save; in the third one I also update the UI.

    For me that's really all there is to it. It works flawlessly up to now.

    Credit goes to iCloudCoreDataStack.

    0 讨论(0)
提交回复
热议问题