3

In my code, I have the following extension for NSManagedObject:

extension NSManagedObject {
    convenience init(context: NSManagedObjectContext) {
        let name = self.dynamicType.entityName()
        let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
        self.init(entity: entity, insertIntoManagedObjectContext: context)
    }
}

Which was working as expected in Xcode 7 / iOS 9 SDK. However, iOS 10 SDK adds a method with the same signature:

/* Returns a new object, inserted into managedObjectContext. This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.
 */
@available(iOS 10.0, *)
public convenience init(context moc: NSManagedObjectContext)

Which makes the compiler unhappy: Initializer 'init(context:)' with Objective-C selector 'initWithContext:' conflicts with previous declaration with the same Objective-C selector

Now, I would like to use the new iOS 10 init if it's available and keep using my extension if the application runs on devices with iOS 9.

Is there a nice way how to achieve this while limiting the changes in existing code? I would like to keep the signature of init in the extension.

Tom Kraina
  • 3,569
  • 1
  • 38
  • 58

1 Answers1

1

Unfortunately, as far as I'm concerned, you must change the signature of your init one way or another. It doesn't have to be a big change though:

extension NSManagedObject {
    convenience init(_ context: NSManagedObjectContext) {
        let name = self.dynamicType.entityName()
        let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
        self.init(entity: entity, insertIntoManagedObjectContext: context)
    }
}

I just removed the external parameter name of context. Now it doesn't conflict with the newly added one.

Then, you can just check the iOS version using the method described in this question, and call the correct initializer!

Community
  • 1
  • 1
Sweeper
  • 213,210
  • 22
  • 193
  • 313