Search code examples
swiftrealm

How to save multi level relationships in Realm database


I started to try out Realm database, but I don't understand how to write this hierachy to the database:

class Address {
 Properties for the address object
}

class Street {
 addresses = List<Address>()
 Plus other properties
}

class Area {
  streets = List<Street>()
}

class Manager {
 areas = List<Area>()
}
  1. If I now add a new area, should I call something like realm.write { areas.append(newAreaObject) } to add it to the database. Will that write all the streets and addresses as well?

  2. What If I just want to add ten new address to a street? According to documentation then List.append functions can only be inside a write statement. So should I do something like

    for i in 0..<10 { addAddress(address) }

and then implement

Street.addAddress(Address)
{
    realm.write {street.append(address)} 
}

or can I just call for i in 0..<10 {street.append(address)} and then call realm.write { areas.add(newAreaObject, update: true) }

  1. If I update the name of an address, should I have a write action there as well?

Just so I do it in the correct way and not do a lot of writes that slows it down. I feels strange to have a write action for each append in each class, for example if you generate an area with ten streets, 100 addresses per street, and for each single append write it to database.

It would be good to just add everything to the lists first and then write it all at the same time to the database.

I have looked at the documentation, but I don't understand. Thanks for any comments!


Solution

  • Regarding #1 and #3:

    All changes to an object (addition, modification and deletion) must be done within a write transaction.

    For #2:

    Since write transactions incur non-negligible overhead, you should architect your code to minimize the number of write transactions.

    That means that it's better to create one transaction for adding objects to the list, so instead of:

    for i in 0..<10 {
        realm.write {
            street.append(address)
        }
    }
    

    you should do

    realm.write {
        for i in 0..<10 {
            street.append(address)
        }
    }
    

    Please, see more at https://realm.io/docs/swift/latest/#writes.