What is the selector syntax for Core Data custom p

2020-07-22 18:25发布

问题:

I am trying to implement a very basic custom migration with Core Data. A single property was initially created as an Integer 16 with values of 0 or 1. In the new model version this property is changed to Boolean and the migration policy below should handle it. I have seen several examples written in Swift and they don't appear to make the accessibility open/public or add @objc to make it accessible to Objective-C. I have done this to eliminate any reason it not working.

I've created the mapping model with the custom policy for the entity mapping with the following expression.

FUNCTION($entityPolicy, "convertInteger:" , $source.active)

It keeps failing because the selector is not recognized. Specifically it gets the following error.

unrecognized selector sent to instance

I have tried many variations.

  • convertInteger:
  • convert(integer:)
  • convertInteger(_:)

I am unable to get any variation to work. What is a valid selector for this expression?

In the Swift code I put an assertion in the initializer and it passes, but I cannot use that same selector in the expression for the policy.

import CoreData

@objc
open class IntegerToBooleanMigrationPolicy: NSEntityMigrationPolicy {

    @objc
    public override init() {
        super.init()
        assert(responds(to: #selector(convert(integer:))), "Policy does not respond to selector!")
    }

    @objc
    open func convert(integer: Int16) -> Bool {
        debugPrint("Converting \(integer) to boolean")
        return integer == 1
    }

}

回答1:

After pasting your code snippet into the Swift REPL, I evaluated the following expression:

20> #selector(IntegerToBooleanMigrationPolicy.convert(integer:))
$R1: Selector = "convertWithInteger:"

That suggests convertWithInteger: is the selector you should use in the mapping expression.