user3804063
user3804063

Reputation: 849

optimistic locking failure iOS swift

Yes of course I did search in the whole internet . But can't get out of this issue.

I got two entity named: Post & PopularPost. (Almost duplicate of one another)

When I fetch the Post and update it's properties like numberoflikes,numberofcomments it's good.

But when I fetch the PopularPost and try to update it's properties then it says "optimistic locking failure"

MY code to fetch and update and save the entity:"PopularPosts".

let postpopFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PopularPosts")
        postpopFetch.predicate = NSPredicate(format: "id = %@", postId)
        let resultp = try? CoreDataManager.sharedInstance.managedObjectContext.fetch(postpopFetch)
        let resultDatap = resultp as! [PopularPosts]

        for object in resultDatap {

            print(object.numberOfHearts)

            if like {
                object.numberOfHearts = object.numberOfHearts + 1
                object.isLiked = true
            }else{
                (object.numberOfHearts > 0) ? (object.numberOfHearts = object.numberOfHearts - 1) : (object.numberOfHearts = 0)
                object.isLiked = false
            }
        }

        do {
            try CoreDataManager.sharedInstance.managedObjectContext.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }

Upvotes: 0

Views: 1684

Answers (2)

lewis
lewis

Reputation: 3182

In my case this was caused by using a newBackgroundContext().

I had a potentially long running task which started when the app went into the background.

Even though it completed before using the app again, I found that all saves made after the background task would fail.

I solved the issue by using the viewContext for the long running task.

Upvotes: 0

Jon Rose
Jon Rose

Reputation: 8563

Generally optimistic locking failure is caused by two different managed object contexts trying to change the same data. I think you can also have this issue even with one context if you are inappropriately accessing it from different threads at the same time. ManagedObjectContexts are not thread safe neither for reading or for writing.

I have seen situation that there is access to a managedObjectContext from the wrong thread and there is a crash much later when on a line of code that is doing nothing wrong. I would recommend to careful search your code for any access to core-data that is not on the main thread. You use [NSThread isMainThread] to check if you are not on the main thread for debugging.

Upvotes: 1

Related Questions