核心数据ios9:多字段唯一约束 [英] core data ios9: multifield unique constraint

查看:84
本文介绍了核心数据ios9:多字段唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道核心数据的新功能是唯一的约束,所以我决定测试它。我创建了简单的模式,当我为一个字段添加约束(例如firstName) - 所有的工作。如果我为另一个字段(lastName)添加约束 - 核心数据为每个字段单独创建两个不同的约束(我试图添加两个字段逗号分隔在一行和每个字段在单独的行 - 没有差别)。



>解决方案

可以为属性组合设置唯一性约束。你是在正确的路径把两个属性放在同一行的约束:





您可能已经发现,由于Xcode的问题,这没有效果:除非您同时修改模型的其他方面(例如更改



如果查看生成的SQL,则使用约束创建表:



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

,当插入新的插入新的值时,这个约束失败(当保存上下文时):

  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

,返回的错误是:

 错误Domain = NSCocoaErrorDomain Code = 133021(null)UserInfo = {conflictList =(
NSConstraintConflict(0x7fbd18d33c10) n lastName,\\\
firstName\\\
):....

7.2.1,使用iOS9.2模拟器;我没有检查以前的版本)。


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).

这篇关于核心数据ios9:多字段唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆