Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique Constraints do not work

I'am using ios 10, xcode 8 (if that even matters, just mentioning everything). So according to wwmd, a fetch request is not needed to check if something is in core data, and then if it is, not save so as to not duplicate. Unique Constraints have been introduced for that matter. So I have an entity called List, with id as an attribute. In contraints, I listed id (as the demonstrator on wwmd did). I also gave the context I'am using a merge policy of NSMergeByPropertyObjectTrumpMergePolicy.

var context: NSManagedObjectContext {
    mutating get {
        if #available(iOS 10.0, *) {
            let context = persistentContainer.viewContext
            context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
            return context
        } else {
            return managedObjectContext
        }
    }

}

To my point, it's not working. I can save the same id and it will Duplicate!!!. and there is absolutely no documentation on this relating to IOS 10. I made it work using swift IO9 managedObjectContext, but cannot make it work with IOS10 persistentcontainer.viewcontext. If someone has a solution for this, it would be immensely appreciated.

like image 546
Ryan Avatar asked Aug 02 '26 20:08

Ryan


2 Answers

Unique Constraints only work when you save the context.

After creating NSMangaedObjects save that NSManagedContext in which they were created.

Yes unique constraints doesnot work if you have relationship in your entity.(I tried this with xcode 7.3 ios9)

like image 115
Anoop Rawat Avatar answered Aug 05 '26 12:08

Anoop Rawat


Solution: I added the mergepolicy in view didload in whichever viewcontroller needed the context. Update: Better solution : as Core data's unique constraints do not work with relationships, i ended up using Core Store which has a wonderful uniqueness algorithm as well as many useful core data wrappers.

like image 27
Ryan Avatar answered Aug 05 '26 14:08

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!