1

I created simple NSBatchUpdateRequest:

let bur = NSBatchUpdateRequest(entityName: "WLWishlist")
bur.predicate = NSPredicate(format: "name = %@", "oldname")
bur.propertiesToUpdate = ["name": "newname"]
bur.resultType = .UpdatedObjectsCountResultType

and then execute them:

do {        
    let result = try NSManagedObjectContext.MR_defaultContext().executeRequest(bur) as? NSBatchUpdateResult
    print("------------- \(result!.result)")
} catch {
    print("error")
}

The output on console is:

------------- Optional(6)

But my NSFetchedResultsController which manage the same objects, does not know that sth was changed. How to inform NSFetchedResultsController about this?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

1

First you have to change resultType to .UpdatedObjectIDsResultType

    bur.resultType = .UpdatedObjectIDsResultType

Once you execute request you have to iterate over NSManagedObjectIDs and refresh them in NSManagedObejctContext. After this you have to performFetch() again your NSFetchedResultsController.

    do {

        let result = try context.executeRequest(bur) as? NSBatchUpdateResult
        if let ids = result?.result as? [NSManagedObjectID] {

            for id in ids {
                let object = context.objectWithID(id)
                context.refreshObject(object, mergeChanges: true)
            }
            try fetchedResultsController.performFetch()
        }

    } catch {
        print("error")
    }
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Wait, if you perform a fetch and expunge the fetch controllers cache, and you perform the batch request on the same context as the fetch controller, why do you need to merge the objects and force them to fault AND perform another fetch? My current experience shows if you perform a fetch, the correct results are reflected. This is ignoring the fact that I'm a bit puzzled on how everyone recommends forcing faults on a batch request. If you're updating 1000 records, I doubt you want the performance hit of iterating and faulting 1000 objects. – TheCodingArt Sep 03 '16 at 19:59