0

I'm working with web app. I have UITableViewController which deals with NSFetchedResultsController. I store tableView's objects through CoreData. When a user refreshes UI I perform server request and then call batch update for each new entity, my CoreData class looks like:

extension DBOrder {
    @NSManaged var comment: String
    @NSManaged var date: NSNumber
    @NSManaged var id: NSNumber
    @NSManaged var maturity_date: NSNumber
    @NSManaged var number_of_tasks: NSNumber
    @NSManaged var price: NSNumber
    @NSManaged var status: String
    @NSManaged var subject: String
    @NSManaged var taskImages: [String]
    @NSManaged var theme: String
}

"id" is unique for each object. "propertiesToUpdate" consists of some fields like "maturity_date": 1470427641000, "status": "some status" and etc. "entityName" is "DBOrder". And privateContext is NSManagedObjectContext type to update entities in background

func updateCoreData(id: NSNumber, entityName: String, propertiesToUpdate: [String: AnyObject], privateContext: NSManagedObjectContext) -> Bool {
    let batchRequest = NSBatchUpdateRequest(entityName: entityName)

    batchRequest.predicate = NSPredicate(format: "id == %@", id)

    if !doesOrderExists(entityName, id: id, context: privateContext) {
        return false
    }

    batchRequest.propertiesToUpdate = propertiesToUpdate
    batchRequest.resultType = .UpdatedObjectIDsResultType

    do {
        let res = try privateContext.executeRequest(batchRequest) as! NSBatchUpdateResult
        let orderIDs = res.result as! [NSManagedObjectID]
        return (orderIDs.count != 0) ? true : false
    } catch {
        print(error)
    }
    return false
}

This function is called for each object that has been loaded from server. If object is already existed then I update it else create the new one.

Finally, the problem: when I use batch update it works incorrect with NSNumber. It always puts NSNumber fields to nil and works as it should with String fields. So, what I'm doing wrong?

Mikhail Maslo
  • 616
  • 6
  • 13
  • I don't think you should be using NSBatchUpdateRequest for this. Because you are updating only one object at a time, you might just as well use a standard fetch, update the object that's returned, and save. – pbasdf Aug 05 '16 at 08:19
  • @pbasdf I will update 1-2 older records and just several fields. So, I think using batch update makes sense here instead standard fetch, update, save mechanism. Of course, I can change all fields type on String, but I want to understand where I wrong – Mikhail Maslo Aug 05 '16 at 09:50

0 Answers0