使用CoreData谓词检查对象

时间:2020-09-28 16:54:34

标签: swift core-data

我使用Core Data查找谓词为“ parentId == 3”的CatalogItem。而且我也想检查该谓词是否存在带有CatalogItem.parentId == id的项目。此“ id”来自第一个查询部分的结果项目。是否可以使用id,我还不知道?

enter image description here

1 个答案:

答案 0 :(得分:0)

我不愿提供这个答案,因为(如@JoakimDanielson在评论中所说),更好的解决方案是实现从CatalogItem到其自身的自反关系。但是,如果这不是一个选择,我认为在this answer上针对类似问题的以下变体应该可以满足您的需求:

let parentFetch = CatalogItem.fetchRequest()
parentFetch.predicate = NSPredicate(format:"parentId == 3")
parentFetch.propertiesToFetch = ["id"]
let ctxtExp = NSExpression(forConstantValue: managedObjectContext)
let fetchExp = NSExpression(forConstantValue: parentFetch)
let fre = NSFetchRequestExpression.expression(forFetch: fetchExp, context: ctxtExp, countOnly: false) 
let childFetch = CatalogItem.fetchRequest()
childFetch.predicate = NSPredicate(format:"parentId IN %@",fre)
... proceed to execute the fetch against the relevant context