How to set the type of NSBatchDeleteResult of a NSBatchDeleteRequest?

Viewed 863

I have some core that performs a Batch delete request:

extension NSManagedObject: Clearable {
    /// Clears all objects of this type in coreData
    static func clearAll() {
        let context = AppDelegate.sharedInstance()?.coreDataHelper.objectContext()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing:self))
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            if let unwrappedContext = context {
                unwrappedContext.shouldDeleteInaccessibleFaults = true
                let result = try unwrappedContext.execute(batchDeleteRequest) as? NSBatchDeleteResult
                DLog("result \(result.debugDescription)")
                switch result!.resultType {
                case .resultTypeCount:
                    DLog("resultTypeCount")
                case .resultTypeObjectIDs:
                    DLog("resultTypeObjectIDs")
                case .resultTypeStatusOnly:
                    DLog("resultTypeStatusOnly")
                }
                if let objectIDArray = result?.result as? [NSManagedObjectID] {
                    let changes = [NSDeletedObjectsKey : objectIDArray]
                    NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [unwrappedContext])
                }
                try context?.save()
            }
        } catch let error as NSError {
            DLog("Error removing : \(error), \(error.localizedDescription)")
        }
    }
}

The code works fine, but the result of the batch delete is always .resultTypeStatusOnly

The documentation here https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html#//apple_ref/doc/uid/TP40016086-CH3-SW2 says under the title Updating Your Application After Execution that

it is important that you notify the application that the objects in memory are stale and need to be refreshed.

And to do that the result type has to be .resultTypeObjectIDs, to be able to trigger the NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [unwrappedContext]) part. It's just not clear how you get that.

How does one set the type of the result?

1 Answers
Related