max
max

Reputation: 51

swift core data migration to change attribute type

I have a iOS app that has a core data database for news. Each of the news entities has a ID attribute, which should be a Integer but until now, it is a String and I want to change it to be a Integer.

Steps I have tried until now:

  1. Created a new model version and changed the type of the ID attribute from String to Int 32
  2. Created a mapping model, where ID has the value expression FUNCTION($entityPolicy, "idToInt:" , $source.id)
  3. Defined a subclass of NSEntityMigrationPolicy where I have defined the idToInt function mentioned above:
import CoreData

class ModelV2MigrationPolicy: NSEntityMigrationPolicy {
    func idToInt(old: String) -> Int32 {
        return Int32(old)!
    }
}
  1. Linked migration policy to mapping model by setting Custom Policy to myapp.ModelV2MigrationPolicy

But if I now try to run my app, it crashes with the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[myapp.ModelV2MigrationPolicy idToInt]: unrecognized selector sent to instance

Any ideas how to fix this?

Upvotes: 3

Views: 760

Answers (1)

Fabien MARIE-LOUISE
Fabien MARIE-LOUISE

Reputation: 21

The problem is that your selector in FUNCTION($entityPolicy, "idToInt:" , $source.id) is wrong.

Based on your method func idToInt(old: String) the selector should be "idToIntWithOld:"

Upvotes: 2

Related Questions