Realm-cocoa: Object property returning nil even if seems to be there.

Created on 14 Apr 2016  路  2Comments  路  Source: realm/realm-cocoa

Goals

Get object property. The property is another object.

Expected Results

Expecting a valid object.

Actual Results

Returning nil.

The result of this

...
            print(localChat.description)
            print(localChat.lastMessage?.description)
            print(localChat.description)
....

Chat {
id = 2204602d-aca2-4566-ae49-70ffa2e2cab8;
lastMessage = Message {
id = 6EE4C3DC-6D29-431D-A175-D359EA782AAF;
};
}

nil

Chat {
id = 2204602d-aca2-4566-ae49-70ffa2e2cab8;
lastMessage = Message {
id = 6EE4C3DC-6D29-431D-A175-D359EA782AAF;
};
}

Version of Realm and Tooling

In the CONTRIBUTING guidelines, you will find a script,
which will help determining these versions.

Realm version: 0.98.7

Xcode version: 7.3 (7D175)

iOS/OSX version: 10.11.4

Dependency manager + version: cocoapods 0.39.0

T-Help

Most helpful comment

@georgepoenaru
I believe you forgot to specify dynamic to lastMessage property. If there is no dynamic attribute on the property, the Realm object cannot invoke Realm's getter method due to dispatch statically by Swift compiler. (description method invoke valueForKey() method internally, it occurs dynamic dispatch. that's why you can see the lastMessage value in the description)

So could you confirm setting dynamic attributes on your model definition?

class Chat: Object {
    ...
    dynamic var lastMessage: Message?
    ...
}

NOTE: RealmOptional and List<T> properties cannot be set dynamic.
See also property cheetsheet: https://realm.io/docs/swift/latest/#cheatsheet

All 2 comments

@georgepoenaru
I believe you forgot to specify dynamic to lastMessage property. If there is no dynamic attribute on the property, the Realm object cannot invoke Realm's getter method due to dispatch statically by Swift compiler. (description method invoke valueForKey() method internally, it occurs dynamic dispatch. that's why you can see the lastMessage value in the description)

So could you confirm setting dynamic attributes on your model definition?

class Chat: Object {
    ...
    dynamic var lastMessage: Message?
    ...
}

NOTE: RealmOptional and List<T> properties cannot be set dynamic.
See also property cheetsheet: https://realm.io/docs/swift/latest/#cheatsheet

Thank you! This was my problem. I thought that object properties can't also be set dynamic.

Was this page helpful?
0 / 5 - 0 ratings