Swift 3 Core Data Delete Object

user6485277 picture user6485277 · Jun 24, 2016 · Viewed 77.6k times · Source

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?)

Answer

Martin R picture Martin R · Jun 24, 2016

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)
    }
}

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.