Search code examples
swiftrealmrealm-list

Realm linking objects and deletions


In Realm, if I have a linkingOjbects relationship set-up, how should I handle deletions and not be left with orphans especially when it's a many-to-many inverse relationship?

Using the Realm Person and Dog examples, assuming that a Person in this instance is a Dog walker and that a Dog can be walked by a different Person on different days

So a Dog object is assigned to multiple Person objects. Each Person object can see the Dog. Assuming the following object structure and data

  Person : Object {
     dynamic var name:String = ""
     let dogs = List<Dog>()
  }

  Dog : Object {
    dynamic var name: String = ""
    let walkers = LinkingObjects<fromType: Person.self, property:"dogs">
  }


Person A
dogs = [Fido,Rover]

Person B
dogs = [Fido, Rover]

Person A no longer needs to walk Fido, so would the correct approach be

   personA.dogs.remove(objectAtIndex:idxOfFido) 

This would update the reference in personA but would it also update the reference in dog?

Secondly if personB also no longer needs to walk Fido I would do

  personB.dogs.remove(objectAtIndex:idxOfFido)

but would this then leave an orphaned reference to Fido in my Dog realm as it is no longer walked by anyone? Would it then be up to me to do a check such as

 if fido.walkers.count == 0 {
     //remove Fido
 }

Solution

  • 1.) linking objects are the "other side of the relationship", so if you update it on one side, then the other side also updates. Removing fido from persons.dog will remove person from dog.walkers.

    2.) just because a dog isn't walked by someone doesn't mean it's dead, so yes, you'd need to delete orphaned dog manually.