Mulgard Mulgard - 2 months ago 8
Swift Question

RLMException: Object type does not match RLMArray type

I have a simple object:

class MyObject : Object {
dynamic var dummyField: String!;
}


and another object which inherits from
MyObject
:

class MyOtherObject : MyObject {
dynamic var anotherDummyField: String!;
}


Now I do the following. I have a Realm List of
MyObject
and I create an instance of
MyOtherObject
and try to save it inside the list:

class Operator {
internal var myObjects: List<MyObject>!;

internal var myObject: MyObject!;

func operate() {
self.myObject = MyOtherObject();
self.myObject.dummyField = "dummy field";
self.myObject.anotherDummyField = "another dummy field";

self.myObjects = List<MyObject>();
self.myObjects.append(myObject); // crash!
}
}


It crashes with the error:

Terminating app due to uncaught exception 'RLMException', reason: 'Object type 'MyOtherObject' does not match RLMArray type 'MyObject'.'


Since
MyOtherObject
is a subclass of
MyObject
I cannot understand why the app is crashing at this point with this error message.

Answer

Realm Lists are not covarient. You can only store objects of exactly the declared type in them.