我认为应该很容易的事情真的很挣扎。
使用Swift 3.0,RealmSwift 2.4.2
我有两个模型,一个使用LinkingObjects与另一个模型呈反比关系。
class SetModel: Object {
dynamic var name = ""
let questions = List<QuestionModel>()
}
class QuestionModel: Object {
dynamic var level = ""
let sets = LinkingObjects(fromType: QuestionModel.self, property: "questions")
}
QuestionModels有多个SetModel。 SetModels有多个QuestionsModels。
SetModel可以有一个名称,如&#39; Food&#39;,&#39; Sport&#39;&#39; Travel&#39;等
在我的代码中的某个时刻,我需要找到一个QuestionModel的子集,它等同于许多不同的过滤选项,其中一个是Sets。 即获得所有容易的问题&#39;在某些集合中。
我获得了许多套装,例如&#39; Food&#39; &安培; &#39;旅游&#39;并且需要找到在他们的“集合”中设置的所有问题。属性。
fileprivate func applyFilters(objects: Results<QuestionModel>) -> Results<QuestionMode> {
var res = objects
// I have a session attribute that stores the values I need to filter on,
// one of which is a List<SetModels>
if (session.sets.count > 0) {
// These are the things I've tried, and the error messages :(
for s in session.sets {
// *** Terminating app due to uncaught exception 'Invalid predicate',
// reason: 'Key paths that include an array property must use
// aggregate operations'
res = res.filter("sets.name == \(s.name!)")
}
for s in session.sets {
// *** Terminating app due to uncaught exception 'Invalid predicate',
// reason: 'Predicate with ANY modifier must compare a KeyPath with
// RLMArray with a value'
res = res.filter("ANY sets.name == \(s.name!)")
}
for s in session.sets {
// *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
// reason: 'Unable to parse the format string "ANY sets == SetModel
res = res.filter("ANY sets == \(s)")
}
// *** Terminating app due to uncaught exception 'Invalid predicate',
// reason: 'Key paths that include an array property must use aggregate
// operations'
res = res.filter("sets.name IN \({'Food', 'Travel'})")
}
// Filter on level
res = res.filter("level == 'easy'")
return res
}
编辑:这里是一个问题集。它显示我可以访问集合并且那里有数据
po self.questionModel.sets
LinkingObjects<SetModel> (
[0] SetModel {
uuid = 5899cb786f6986.79052132;
name = Action;
questions = RLMArray <0x7f9a529a6910> (
[0] QuestionModel {
question = What can you climb?;
responses = Tree;
},
[1] QuestionModel {
question = How could you get into town?;
responses = Bus;
}
);
},
[1] SetModel {
uuid = 5899cbc2938b87.61048461;
name = Travel;
questions = RLMArray <0x7f9a52c05d60> (
[0] QuestionModel {
question = How could you get into town?;
responses = Bus;
}
);
}
)
任何帮助非常感谢
答案 0 :(得分:0)
let predicate = NSPredicate(format:"SUBQUERY(sets, $s, $s.name IN %@).@count > 0", ['Demo', 'Food'] )
res = res.filter(predicate)
老实说,有时候我觉得自己像一个学徒魔术师随便说法术:)