Core Data “Unique Constraint” raises exceptions when it works?

戏子无情 提交于 2019-12-08 13:50:21

问题


Several years ago, Core Data added a feature in data models which, with zero code, during save, automatically merges new insertions with existing objects when certain attributes which you specify have equal values. This feature is called Unique Constraint. Very nice. But it seems to raise exceptions when it does this merging.

I forked a little project demonstrating this feature which was written by Zachary Orr in 2015 in Objective-C. This project is discussed in the first answer of this Stack Overflow question, which also has a cute video showing the objects getting merged when user taps Save. My fork of this project converts it to Swift 5.

Running either the Objective-C or Swift 5 project in iOS 12, I am able to reproduce Zachary's video showing proper operation only if I disable my user breakpoint on objc_exception_throw (or All Objective-C exceptions). So, either Zachary did not have this breakpoint enabled when he recorded that video, or these exceptions were not raised in iOS 9.

With this breakpoint enabled, upon tapping the + button enough times to add duplicate entries, and then tapping Save, multiple exceptions are raised within the NSManagedObjectContext.save() execution. Specifically, if I add N duplicate entries, I get N+1 Constraint violation exceptions and N+2 optimistic locking failure exceptions. (To see the exception description when it breaks, select objc_exception_throw at the top of the call stack, then command po $arg1 in the debugger console.) Examples:

(lldb) po $arg1
Constraint violation
(null)

(lldb) po $arg1
optimistic locking failure
(null)

After I command the debugger to continue (N+1)+(N+2) times, the app continues to run, the duplicates are merged as expected, and all is fine.

It is common wisdom that such exceptions are usually due to not setting a proper merge policy on the context. But in both projects the context has NSMergeByPropertyObjectTrumpMergePolicy. I have verified that this is working by printing the expression

context.mergePolicy == NSMergeByPropertyObjectTrumpMergePolicy

just before calling save(). It prints true.

It looks like @KMC asked about such exceptions in 2017 but never got an answer.

Update: I've submitted this to Apple Bug Reporter: 50726397. While waiting for them to respond, is there something wrong in my code, or do the kids just not worry about exceptions nowadays?

来源:https://stackoverflow.com/questions/56108300/core-data-unique-constraint-raises-exceptions-when-it-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!