Search code examples
core-datansmanagedobjectnsmanagedobjectcontextswift3ios10

delete core data managed object with Swift 3


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


Solution

  • 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.