Search code examples
iosswiftcore-dataswift3

Swift 3 Core Data Delete Object


Unfortunately the new Core Data semantics make me crazy. My previous question had a clean code that didn't work because of incorrect auto generation of header files. Now I continue my work with deleting objects. My code seems to be very simple:

func deleteProfile(withID: Int) {
    let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
    fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
    let object = try! context.fetch(fetchRequest)
    context.delete(object)
} 

I did a "hard" debug with print(object) instead of context.delete(object) and it showed me the right object. So I need just to delete it.

P.S. there is no deleteObject. Now NSManagedContext has only public func delete(_ sender: AnyObject?)


Solution

  • The result of a fetch is an array of managed objects, in your case [Event], so you can enumerate the array and delete all matching objects. Example (using try? instead of try! to avoid a crash in the case of a fetch error):

    if let result = try? context.fetch(fetchRequest) {
        for object in result {
            context.delete(object)
        }
    }
    
    do {
        try context.save()
    } catch {
        //Handle error
    }
    

    If no matching objects exist then the fetch succeeds, but the resulting array is empty.


    Note: In your code, object has the type [Event] and therefore in

    context.delete(object)
    

    the compiler creates a call to the

    public func delete(_ sender: AnyObject?)
    

    method of NSObject instead of the expected

    public func delete(_ object: NSManagedObject)
    

    method of NSManagedObjectContext. That is why your code compiles but fails at runtime.