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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With