Search code examples
iosswiftcore-datafetchnsmanagedobject

Swift Core Data: How to fetch all items in array?


I want to delete the existing content of my NSManagedObjects Weather and Currently.

let entityNames = ["Weather", "Currently"]
for entityName in entityNames {
    let fetchRequest = NSFetchRequest(entityName: entityName)
    let objects = try(context.execute(fetchRequest)) as? [NSManagedObject]
    for object in objects! {
        context.deletedObjects(object)
    }
}

However using this code, I get an error on the 3rd line stating:

Generic parameter 'ResultType' could not be inferred


Solution

  • You have to specify the generic type of the fetch request

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
    

    then you can even omit the result type

    let objects = try? context.execute(fetchRequest)
    

    And there is a typo. You probably mean

    context.deleteObject(object)
    

    In macOS 10.11+/ iOS 9.0+ you are encouraged to use NSBatchDeleteRequest