How to test why your iCloud Core Data store was changed

When you’re using iCloud with Core Data you need to subscribe and react to the NSPersistentStoreCoordinatorStoresDidChange notification. This will tell you when Core Data was able to transition off the “fake” store and is using the “real” store. It will coincide with the log entry “Using local storage: 0”.

Sometimes you need to know why this has happened so you can react accordingly. Here’s how:

When you react to the above, bring the notification object into your even handler method. This will let you query its userInfo dictionary which will hold the key to why the stores have been changed:

- (void)storesDidChange:(NSNotification *)notification {
    
    // Tell me: why did my stores changes?
    NSNumber *transitionType = [notification.userInfo objectForKey:NSPersistentStoreUbiquitousTransitionTypeKey];
    int theCause = [transitionType intValue];
    
    switch (theCause) {
        case NSPersistentStoreUbiquitousTransitionTypeAccountAdded: {
            
            // account was added
        }
            break;
        case NSPersistentStoreUbiquitousTransitionTypeAccountRemoved: {
            
            // account was removed
        }
            break;
        case NSPersistentStoreUbiquitousTransitionTypeContentRemoved: {
            
            // content was removed
        }
            break;
        case NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted: {
            
            // initial import
        }
            break;
            
        default:
            break;
    }
}

Here we grab the NSPersistentStoreTransitionKeyType entry from the userInfo dictionary. It’s an NSNumber, enumerated to four keys. To test those with a switch statement I’m converting the NSNumber into an int.

Use this to check if an iCloud account has been changed, or if this is the first time an iCloud store has been started on the current device.

I’m explaining this as part of my screencast about using iCloud and Core Data:





Leave a Reply