我有一个模型类别,关系属性文章是一个NSOrderedSet。 现在我想用满足某个条件的文章获取所有类别,在SQL中我会写:
SELECT *
FROM Category AS cat
JOIN Article AS art ON art.categoryId = cat.categoryId AND art.gender='m';
我尝试过:
NSPredicate(format: "articles.gender like %@ OR articles.gender = %@", gender.lowercased(), "n")
我收到以下错误:
***由于未捕获的异常'NSInvalidArgumentException'终止应用,原因:'此处不允许使用多对键'
完整代码:
let ctx = self.Context()
var gender = UserDefaults.standard.string(forKey: "gender_preference") ?? "*"
if gender.uppercased() == "N" { gender = "*" }
// Create Fetch Request
let fetchRequest: NSFetchRequest = ArticleCategory.fetchRequest()
let predicate = NSPredicate(format: "articles.gender like %@ or articles.gender = %@", gender, "n")
fetchRequest.predicate = predicate
// sort by name
let sort = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sort]
do {
let result = try ctx.fetch(fetchRequest)
return result
} catch {
print(error)
}
return []
亲切的问候
编辑:
答案 0 :(得分:0)
我发现使用SUBQUERY更可靠,而不是ANY,ALL,NONE或SOME,尤其是复合条款。如果符合条件的文章计数大于零,则获取其中任何文章满足条件的类别等同于获取:
let predicate = NSPredicate(format: "SUBQUERY(articles, $a, $a.gender like %@ OR $a.gender == %@).@count > 0", gender, "n")