Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the selector syntax for Core Data custom policies?

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
    }

}
like image 210
Brennan Avatar asked Jun 19 '17 19:06

Brennan


People also ask

How do I use CoreData?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

What is transformable in core data?

When you declare a property as Transformable Core Data converts your custom data type into binary Data when it is saved to the persistent store and converts it back to your custom data type when fetched from the store. It does this through a value transformer.


1 Answers

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.

like image 184
bdash Avatar answered Oct 08 '22 23:10

bdash