I look forward to your kind cooperation.
iOS 8.0
Swift 2.1
Realm 0.96.3
I would like to define two classes with parent-child relationships and extract Parent with one or more Child with status true.
class Child:Object{
dynamic var status = false
dynamic var name=""
convenience init(name:String) {
self.init()
self.name = name
}
}
class Parent:Object {
let children=List<Child>()
dynamic var name=""
convenience init(name:String) {
self.init()
self.name = name
}
}
classViewController:UIViewController {
let realm=try!Realm()
override func viewDidLoad(){
super.viewDidLoad()
setSampleData()
procedure()
}
func procedure() {
letpredicate=NSPredicate(format: "SUBQUERY(children,$c,$c.status==true).@count>0")
print(realm.objects(Parent).filter(predicate).description)
}
funcsetSampleData(){
try!realm.write{
self.realm.deleteAll()
let parent1 = Parent(name: "Parent1")
let parent2 = Parent(name: "Parent2")
let parent3 = Parent(name: "Parent3")
letchild1 = Child(name: "Child1")
letchild2 = Child(name: "Child2")
letchild3 = Child(name: "Child3")
letchild4 = Child(name: "Child4")
letchild5 = Child(name: "Child5")
self.realm.add (parent1)
self.realm.add (parent2)
self.realm.add (parent3)
self.realm.add (child1)
self.realm.add (child2)
self.realm.add(child3)
self.realm.add (child4)
self.realm.add(child5)
child1.status=false
child2.status=true
child3.status=false
child4.status=true
child5.status=false
parent1.children.append(child1)
parent1.children.append(child2)
parent2.children.append(child3)
parent2.children.append(child4)
parent3.children.append(child5)
}
}
override funcdidReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The build will succeed, but the following error will appear:
Terminating app due to uncaught exception 'Invalid predict expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'
I don't think you understand SUBQUERY, but
It's hard to understand even if I look into it.
Can someone give me some advice?
Subquery is not yet available in Realm.
By the way, if status
is to extract Parent
with one or more Child
of true
, you can do it with the following code more easily:
Running with the code in the example returns parent1
and parent2
(except that parent3
has only status
with false
).
Is this the answer?
let parents=realm.objects(Parent).filter("ANY children.status==true")
© 2024 OneMinuteCode. All rights reserved.