Chapter 4: Batch Updates question

Hi everyone!

I have a little question regarding the Batch updates example in chapter 4.

In the example the code updates all “Venues” to be my favorites like this:

let batchUpdate = NSBatchUpdateRequest(entityName: "Venue")
batchUpdate.propertiesToUpdate = [#keyPath(Venue.favorite) : true]
batchUpdate.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
batchUpdate.predicate = NSPredicate(format: "%K == %@", #keyPath(Venue.priceInfo.priceCategory), "$$$")

do {
  let batchResult = try coreDataStack.managedContext.execute(batchUpdate) as! NSBatchUpdateResult
  print("Records updated \(batchResult.result!)")
} catch let error as NSError {
  print("Could not update \(error), \(error.userInfo)")
}

But what if I just want to update the ones with the price category = “$” ?

I this predicate to the NSBatchUpdateRequest :

batchUpdate.predicate = NSPredicate(format: “%K == %@”, #keyPath(Venue.priceInfo.priceCategory), “$$$”)

But the app crashes with this error:

Bubble Tea Finder[77429:6687874] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘keypaths (joins) not supported in batch update statements’

Is there a way to update this Venues without fetching them in memory first?

Thanks!

@pietrorea Can you please help with this when you get a chance? Thank you - much appreciated! :]

@xlsmearlx Thanks very much for your question!

One of the advantages of using predicates is that you have the option of using multiple predicates together, so you don’t have to put all of your criteria into a single predicate. What I would suggest is use the existing predicate, and add another predicate to filter the results to include only those with $$$$. After combining the predicates, you should be able to pull the results you are looking for.

I hope this helps!

All the best!