ios 如何为 Core Data 中的某些字段添加唯一约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21130427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add unique constraints for some fields in Core Data
提问by malcoauri
I use Xcode for iOS development. I have some entity (for example, User), and I need to set unique constraint for his name, but I can't find how I can do it through visual editor. Is it possible to do it through GUI? Or it's possible through code only? I will be glad to get some screenshot.
我使用 Xcode 进行 iOS 开发。我有一些实体(例如,用户),我需要为他的名字设置唯一约束,但我找不到如何通过可视化编辑器来做到这一点。是否可以通过 GUI 来完成?还是只能通过代码?我会很高兴得到一些截图。
回答by Zachary Orr
There's a new section in the sidebar when selecting an entity in the editor for Core Data. You can set what constraint(s) you want to be unique across all instances of an entity
在编辑器中为 Core Data 选择实体时,侧栏中有一个新部分。您可以设置您希望在实体的所有实例中唯一的约束
For automatic conflict resolution during saves, you'll need to make sure you've got a merge policyset for your managed object context or else you'll just get errors when saving (which might actually be what you want)
为了在保存期间自动解决冲突,您需要确保为托管对象上下文设置了合并策略,否则保存时只会出错(这实际上可能是您想要的)
[managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
The "Swift version" is exactly the same
“Swift 版本”完全一样
managedObjectContext.mergePolicy = .mergeByPropertyObjectTrumpMergePolicyType
Keep in mind conflict resolution only happens during saves, and not inserts. So if you're making use of a NSFetchedResultsController you will see entities with non-unique constraints as they're inserted.
请记住,冲突解决仅在保存期间发生,而不是在插入期间发生。因此,如果您正在使用 NSFetchedResultsController,您将在插入时看到具有非唯一约束的实体。
If you want to sure you have no entities with non-unique constraints in your managed object context without saving (if you're making use of a FRC), this answeris still probably the best way to go. Although, keep in mind, it's expensive if you're doing a lot of inserts, since NSFetchRequests are expensive operations.
如果您想确保在不保存的情况下在托管对象上下文中没有具有非唯一约束的实体(如果您正在使用 FRC),这个答案仍然可能是最好的方法。但是,请记住,如果您要进行大量插入操作,它会很昂贵,因为 NSFetchRequests 是昂贵的操作。
Sample code for this demo can be found here
可以在此处找到此演示的示例代码
回答by Nitin Nain
Swift solution:
迅捷解决方案:
As noted in the other answer, you can have unique constraints in Core Data for iOS9 onwards.
如另一个答案中所述,您可以在 iOS9 以后的 Core Data 中设置唯一约束。
To do this, first add constraints to the Entity from the Core Data Editor (explaination in Zachary's answer).
为此,首先从核心数据编辑器向实体添加约束(在 Zachary 的回答中进行了解释)。
Then add this line in code:
然后在代码中添加这一行:
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
Note:The uniqueness is checked when you do managedObjectContext.save()
not while you're just adding objects to the managed object.
注意:当您managedObjectContext.save()
只是向托管对象添加对象时不检查唯一性。
NSMergeByPropertyObjectTrumpMergePolicy
is just one of the merge policies, which overwrites the old value with the new one. You might want to check the documentation for other options.
NSMergeByPropertyObjectTrumpMergePolicy
只是合并策略之一,它用新值覆盖旧值。您可能需要查看文档以了解其他选项。
回答by Jery Starr
swift Version Is Easy Disclaimer : If You Have Conflicting information please delete piror to implementation. Else App will not run. Solution Delete from device and start again
swift 版本很容易免责声明:如果您有冲突的信息,请删除执行前的内容。否则应用程序将无法运行。解决方法从设备中删除并重新启动
steps are:
步骤是:
- Open Core Data File (projectname.xcdatamodeld)
- Click on the entity name (needs to be highlighted)
- Right Side of screen (in class section) find constraints (hit the plus button)
- Right click to edit info rename to Attribute.
- 打开核心数据文件 (projectname.xcdatamodeld)
- 点击实体名称(需要高亮显示)
- 屏幕右侧(在课堂部分)找到约束(点击加号按钮)
- 右键单击以编辑信息重命名为属性。
// now to add the code in you core data container
// 现在在核心数据容器中添加代码
- open AppDelegate.swift file and scroll into the coredata stack (" // MARK: - Core Data Saving support ")
- update the code for the static func saveContext() { let variable = persistentContainer.viewContext "
- 打开 AppDelegate.swift 文件并滚动到 coredata 堆栈(“// MARK: - Core Data Saving support”)
- 更新静态 func saveContext() { let variable = persistentContainer.viewContext 的代码
//now make this simple call that manages update process
//现在进行这个管理更新过程的简单调用
variable".mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy"
变量".mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy"
// clear understanding
// 清晰的理解
static func saveContext () {
let context = persistentContainer.viewContext
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
// you need that line
if context.hasChanges {
do {
try context.save()
} catch {