loading...

Composition in Realm

onmyway133 profile image Khoa Pham ・1 min read

Original post https://github.com/onmyway133/blog/issues/13

There is time we have models that have some kind of inheritance, like Dog, Cat, Mouse can be Animal. We can use composition to imitate inheritance, we just need to make sure it has unique primary key

Cat and Dog

These are pretty much basic Realm objects

class Dog: Object {
  dynamic var id: Int = 0

  required convenience init(json: [String: Any]) {
    self.init()
    id <- json.integer(key: "id")
  }
}

class Cat: Object {
  dynamic var id: Int = 0

  required convenience init(json: [String: Any]) {
    self.init()
    id <- json.integer(key: "id")
  }
}

Animal

Here Animal can contain either dog or cat, we can add more if there are many other "inheritance" of Animal. The required init makes sure Animal can only be init with 1 type of child class

class Animal: Object {
  dynamic var id: Int = 0

  dynamic var cat: Cat?
  dynamic var dog: Dog?

  required convenience init(cat: Cat) {
    self.init()
    self.cat = cat
    self.id = cat.id
  }

  required convenience init(dog: Dog) {
    self.init()
    self.dog = dog
    self.id = dog.id
  }
}

Posted on by:

onmyway133 profile

Khoa Pham

@onmyway133

My apps https://onmyway133.com/apps/

Discussion

markdown guide