Search code examples
iosxcodecore-dataxcdatamodel

How to change attribute type in xcdatamodel?


I'm a newbie that is assigned to gigantic project. I have found a minor bug that needs fixing but i don't know exactly how.

Ok here it is. issueNumber attribute in Xcode's core data model is set to Integer 64. I need to change it to String, so the bug would be fixed, but when i change attribute type from Integer 64 to String, my app crashes with gigantic output that starts like this:

CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/Apple/Library/Developer/CoreSimulator/Devices/67D17D00-2AF8-4BC4-ABB7-091C95D02F35/data/Containers/Data/Application/B94B1310-4A63-4F91-AE7B-5F625697B3E2/Library/iMagDocument.sqlite options:{ NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; NSSQLitePragmasOption = { synchronous = OFF; }; } ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error 134130.)" UserInfo=0x7f405ef0 {URL=file:///Users/Apple/Library/Developer/CoreSimulator/Devices/67D17D00-2AF8-4BC4-ABB7-091C95D02F35/data/Containers/Data/Application/B94B1310-4A63-4F91-AE7B-5F625697B3E2/Library/iMagDocument.sqlite, metadata={ NSPersistenceFrameworkVersion = 519; NSStoreModelVersionHashes = {

And it goes and goes... Here is what i do: i change type in data model from Integer 64 to String:

Ok what am I doing wrong? There must be something that I'm obviously missing, so the app crashes every time i change the attribute type.


Solution

  • This is really complex problem. You can't simply change datatype of an attribute. The error you see means that core data is not able to migrate your data to the new version.

    1) Create new model version instead and set new data type there. See https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/creating_new_version.html

    2) Set new model version to be used. https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/setting_current_version.html

    3) You have to add your persistent store with options NSMigratePersistentStoresAutomaticallyOption and NSInferMappingModelAutomaticallyOption.

    NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: [NSNumber numberWithBool:YES],
                              NSInferMappingModelAutomaticallyOption: [NSNumber numberWithBool:YES]
                              };