Reputation: 660
So I have been learning Realm in Swift lately and I come across with a design problem regarding a potential notification between data models. It would be greatly appreciated if someone is willing to shed some insight.
// Class A is what users mainly interact with
Class A: Object {
dynamic var propertyA = ""
dynamic var propertyB = ""
dynamic var propertyC = ""
override static func primaryKey() -> String? {
return "propertyA"
}
}
// Class B is what the server interacts with, like data feeding
Class B: Object {
dynamic var propertyA = ""
dynamic var propertyX = ""
dynamic var propertyY = ""
dynamic var propertyZ = ""
override static func primaryKey() -> String? {
return "propertyA"
}
}
I have set a notification block for Object A
inside the controller. So whenever changes take place in resultObjectsA
, the notification block will get triggered.
let resultObjectsA = realm.objects(A).filter('predicate1')
let notificationTokenA = resultObjectsA.addNotificationBlock {
...
}
In the app that I am building, the user can select a set of Object A
, and the app will query the status of the selection set from the server. The return results will be stored/presented in Object B
. Now, I need to write a query/predicate for Object B
:
let resultObjectsB = realm.objects(B).filter('predicate2')
such that propertyA
in resultObjectB
entries can be found in propertyA
in resultObjectsA
entries, like a one-to-one mapping.
I am not sure if such predicate is doable. If there are other ways to achieve what I would like to do here, I am more than keen to learn as well.
Upvotes: 2
Views: 458
Reputation: 7350
To query all (actually there should be able one object because of primary key) objects B
where objectB.propertyA == objectA.propertyA
use:
let resultObjectsB = realm.objects(B).filter('propertyA = %@', objectA.propertyA)
Another option is to use One-to-One relationship between A
and B
, learn more at https://realm.io/docs/swift/latest/#to-one-relationships
Upvotes: 1