1

Swift 3 has migrated my code and changed:

 context.deleteObject(myManagedObject)

to

 context.delete(myManagedObject)

this is compiling fine (XCode 8b3) but at runtime complaining that the context does not have a function/selector delete(managedObject)

Here is the runtime error:

[NSManagedObjectContext delete:]: unrecognized selector sent to instance

My code is very basic:

func delete()
{
    let appDel: AppDelegate = UIApplication.shared().delegate as! AppDelegate

    if let context: NSManagedObjectContext = appDel.managedObjectContext
    {
        context.delete(exerciseData)
        appDel.saveContext()
    }
}

Why is it no longer working?

Thanks

Greg

Greg Robertson
  • 2,317
  • 1
  • 16
  • 30

1 Answers1

2

From the Xcode 8 beta 3 - Release Notes

Known Issues in Xcode 8 beta 3 – Swift Compiler

Attempting to use NSManagedObjectContext's delete(:) method may result in calling the UIKit-added delete(:) method on NSObject instead (part of the UIResponderStandardEditActions category) if the argument is optional (including ImplicitlyUnwrappedOptional). (27206368)

Workaround: Manually unwrap the optional value using if let or !.

You need to check if this holds true in your case.

Khundragpan
  • 1,952
  • 1
  • 14
  • 22
  • Good catch .... exerciseData is an optional type Exercise! I read the release notes but missed this. Thanks. To fix I unwrapped exerciseData with: if let exerciseToBeDeleted: Exercise = exerciseData { //delete code } – Greg Robertson Jul 21 '16 at 15:56
  • One clarification: I had the situation where I had an optional reference to both the `NSManagedObjectContext` instance, and an `NSManagedObject` instance. I needed to use `if let` or `!` on the *`NSManagedObject`*, not the context... – andrewcbancroft Aug 04 '16 at 03:49