0

I want to migrate to from Realm 0.98 to 1.0.2 but I struggle with LinkingObjects used in inheritance. I can not override the linkingObjects property as before.

Simplified my model exists of a Person that has pets and cats. Cat is a subclass of Pet (as it shared properties which I omitted here). It is important to be handle cats in a separate list in the persons. Lets just assume it's an awesome cats app that also has some support for other pets.

In 0.98 is looks like this:

class Person: Object {
    let pets = List<Pet>()
    let cats = List<Cat>()
}

class Pet: Object {
    var linkedOwner: Person? {
        get {
            return linkingObjects(Pet.self, forProperty: "pets").first
        }
    }
}

class Cat: Pet {
    override var linkedOwner: Person? {
        get {
            return linkingObjects(Cat.self, forProperty: "cats").first
        }
    }
}

I since linkingObjects is used in the getter I can easily override it to change the property from "pets" to "cats".

Now since 1.0 using LinkingObjects instead linkingObjects it is different, for example as described here:

class Person: Object {
    let pets = List<Pet>()
    let cats = List<Cat>()
}

class Pet: Object {
    let linkedOwners = LinkingObjects(fromType: Person.self, property: "pets")
    var linkedOwner: Person? {
        get {
            return linkedOwners.first
        }
    }
}

class Cat: Pet {
    // this does not compile: Cannot override with a stored property 'linkedOwners'
    override let linkedOwners = LinkingObjects(fromType: Person.self, property: "cats") 

    // linkedOwner would be the same so we don't need to override anymore 
}

How can I change / override the property used for the LinkingObjects in the Cat class?

martn_st
  • 2,576
  • 1
  • 24
  • 30

2 Answers2

2

How can I change / override the property used for the LinkingObjects in the Cat class?

The short answer is, you can't change the property used for a LinkingObjects. If you want a subclass to expose LinkingObjects from a different property, you'll need to declare a new property of type LinkingObjects, and use that instead.

bdash
  • 18,110
  • 1
  • 59
  • 91
-1

As @bdash mentioned it's not feasible the old way. Hence I ended up creating a new base class that provides an abstract property to be overriding with a forwarding to the actual specific LinkingObjects property.

class Person: Object {
    let pets = List<Pet>()
    let cats = List<Cat>()
}

class Animal: Object {
   var linkedOwner : Person? { fatalError("override me!") }
}

class Pet: Animal {
    private let linkedOwners = LinkingObjects(fromType: Person.self, property: "pets")
    override var linkedOwner: Person? { return linkedOwners.first }
}

class Cat: Animal {
    private let linkedOwners = LinkingObjects(fromType: Person.self, property: "cats") 
    override var linkedOwner: Person? { return linkedOwners.first }
}
martn_st
  • 2,576
  • 1
  • 24
  • 30