如何针对 CoreData 中的多个关系执行复合查询

How to perform a compound query against to many relationships in CoreData

我正在寻求帮助以了解 NSPredicates 以及如何查询 CoreData。这是我拥有的:

我有两个实体:1. 代表某些数据的 "capture" 的捕获,它与 2. 身份标签有一对多的关系。

我希望从特定的 "Captures" 集合中获取一组 "Identity" 标签。即我想知道名称 'X' 的所有捕获的唯一身份,这些身份也被标记为 Int 'y'.

在 swift 中,我会这样建模:

let captures: [Capture]
let identities = captures.flatmap({ [=10=].identities }).filter({ [=10=].id == "y" })
let uniqueIdentitiesOfParticularType: Set<Identity> = Set(identities.flatMap({ [=10=].name })

有什么帮助吗?

首先,一定要从 Predicate Programming Guide 开始,其中详细介绍了这方面的内容。具体见"Using Predicates with Core Data."

如果你想小心点错的话,你的解决方案可能是这样的:

let request = NSFetchRequest(entityName: "Capture")
let id = "y"
request.predicate = NSPredicate(format: "id == %@", id)
let identities = try context.executeFetchRequest(request) as NSArray
let names = identities.valueForKeyPath("@distinctUnionOfObjects.name")

请注意,iOS 10 为 Swift 添加了更好的桥梁(您可能不需要 as NSArray),但我还没有真正探索它们。

有关 @distinctUnionOfObjects 及其朋友的更多信息,请参阅 Collection Operators