Search code examples
iosxcodeswiftcore-datacore-data-migration

Is Core Data Model Migration Required when changing Attribute Type from Int16 to Int64


I have changed attribute type of my data model from Int16 to Int64. Is migration required for it or it will automatically work as its the same data type Int. Please guide.


Solution

  • Yes you can change attribute type and migrate your datastore in core-data but for that while creating/configuring your NSPersistentStoreCoordinator you need to set few option which i have mentioned below. This is call LightWeight Migration in core-data that we are doing here.

    Update your persistentStoreCoordinator initialiser method with following code.

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
        if (_persistentStoreCoordinator != nil) {
            return _persistentStoreCoordinator;
        }
    
        // Create the coordinator and store
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
        // *** add support for light weight migration ***
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                                 nil];
    
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StoreName.sqlite"];
        NSError *error = nil;
    // *** Add support for lightweight migration by passing options value ***
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    
        return _persistentStoreCoordinator;
    }
    

    You can read more about core-data migration at following sites.

    1. Apple official documentation

    2. Other site