NSFetchedResultsController plus NSBatchUpdateRequest is equal to NSMergeConflict. What am I doing wrong?

I got NSFetchedResultsControllerthat I created using NSManagedObjectContext. I am fetching using this context.

I also have NSBatchUpdateRequestone that I installed using the same NSManagedObjectContext. I execute the request using the same NSManagedObjectContext.

When I execute a query using NSBatchUpdateRequest, I see that all my data has been updated. If I restart the application, any fetch using NSFetchedResultsControlleralso works.

The problem is that I do not restart the application and that I perform both operations one after another, I got an error NSMergeConflict (0x17427a900) for NSManagedObject (0x1740d8d40) with objectID '0xd000000001b40000...when I call the method savefrom my context.

I know the problem is with changing the same data at the same time, but I don’t know what the solution is? One could go through the class NSMergePolicy, but I doubt it is a clean way to solve my problem.

What should I do? Are there two different contexts? (How?)

+4
source share
1 answer

Well, it looks like I could find how to do this, but if you see something wrong, let me know.

When you perform a batch update, you have the opportunity to get the result, be it nothing, the number of updated rows or a list of updated object identifiers. You must choose the latter.

executeRequest , , , NSManagedObject Faults - objectWithID . , Faults Core Data, .

NSManagedObject, , , refreshObject.

, performFetch fetchedResultsController, , .

, - .

:

let batchUpdate = NSBatchUpdateRequest(entityName: "myEntity")
batchUpdate.propertiesToUpdate = ["myPropertieToUpdate" : currency.amountToCompute]
batchUpdate.affectedStores = managedContext.persistentStoreCoordinator?.persistentStores

batchUpdate.resultType = .UpdatedObjectIDsResultType

var batchError: NSError?
let batchResult = managedContext.executeRequest(batchUpdate, error: &batchError) as NSBatchUpdateResult?
if let result = batchResult {
    println("Records updated \((result.result as [NSManagedObjectID]).count)")

    // Extract Object IDs
    let objectIDs = result.result as [NSManagedObjectID]

    for objectID in objectIDs {
        // Turn Managed Objects into Faults
        let nsManagedObject: NSManagedObject = managedContext.objectWithID(objectID)

        if let managedObject = nsManagedObject as NSManagedObject? {
            managedContext.refreshObject(managedObject, mergeChanges: false)
        }
    }

    // Perform Fetch
    var error: NSError? = nil
    if !fetchedResultsController.performFetch(&error) {
        println("error: + \(error?.localizedDescription), \(error!.userInfo)")
    }
} else {
    println("Could not update \(batchError), \(batchError!.userInfo)")
}

: :

http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164

http://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/

+4

All Articles