简体   繁体   中英

core data ios9: multifield unique constraint

I know that new feature of core data is unique constraints so I decide to test it. I created simple schema and when I add constraint for one field (firstName for example) - all works. If I add constraint for another field (lastName) - core data creates two different constraints for each field individually (I tried add two fields comma separated in one line and each field in separate line - no difference). But I want unique constraint for combination firstName + lastName, is it possible?

Thank you for reply!

It is possible to set uniqueness constraints for a combination of attributes. You were on the right path putting both attributes on the same line in the constraints:

数据模型编辑器快照

You may have found this had no effect due to a problem with Xcode: the constraints are not actually updated in the model unless you modify some other aspect of the model at the same time (eg. change an attribute type and then change it back).

If you look at the SQL being generated, the table is created with a constraint:

CREATE TABLE ZSTOREOBJECT ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ...., CONSTRAINT ZLASTNAME_ZFIRSTNAME UNIQUE (ZLASTNAME, ZFIRSTNAME))

and when you insert new insert new values which fail this constraint (when the context is saved):

CoreData: sql: COMMIT
CoreData: sql: BEGIN EXCLUSIVE
CoreData: sql: INSERT INTO ZSTOREOBJECT(Z_PK, Z_ENT, Z_OPT) VALUES(?, ?, ?)
CoreData: sql: UPDATE ZSTOREOBJECT SET ZLASTNAME = ?, ZFIRSTNAME = ? WHERE Z_PK = ?
CoreData: sql: ROLLBACK

and the error returned is:

Error Domain=NSCocoaErrorDomain Code=133021 "(null)" UserInfo={conflictList=(
"NSConstraintConflict (0x7fbd18d33c10) for constraint (\n    lastName,\n    firstName\n): ....

(This works in Xcode 7.2.1, with the iOS9.2 simulator; I haven't checked prior versions).

It seems that Xcode's typical behavior of persisting changes to disk on Run doesn't apply when setting constraints in the model editor. (Xcode 7.3, in my case.) 😞

Solution? Pretend it's 1990 all over again and hit ⌘-S after you change the constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM