user3179636
user3179636

Reputation: 569

Realm object child of Realm Object

I have two Realm Objects. IdPair and IdPairScore. IdPair is a simple class with a couple of string identifiers that is used to identify a particular class that I have.

IdPairScore has an integer score as well as an IdPair in order to identify which score it is as shown below.

class IdPairScore: Object {
    var id:IdPair? 
    var totalRight:Int = 0
}

When the app starts up I get all of the saved IdPair's by the following line of code:

let pairs = realm.objects(IdPair)

The problem is that this picks up the IdPairs saved as the child of the IdPairScore's. For example if I save one IdPairScore and then run the line of code above "pairs" will have one value!!!

I anticipated that if I save an "IdPair" individually it would retrieve it with the line above. If I save it as a property of an "IdPairScore" it would NOT retrieve it with the line of code above. Thanks.

Upvotes: 1

Views: 802

Answers (1)

TiM
TiM

Reputation: 16021

This is intended behaviour. Adding a Realm object as a child object of another type of object doesn't make it exclusive to that object. It is added to Realm just like any other object and then a relationship between it and the linking object is established.

If you need a mechanism to determine if an object currently belongs to another object, you can use Realm's inverse relationships feature

class IdPair: Object {
   var parentScores = LinkingObjects(fromType: IdPairScore.self, property: "id")
}

You can use these properties in queries to easily filter out only the ones that don't have a parent object.

Upvotes: 2

Related Questions