Why is "@objc dynamic" required?


Hi all,

I’m extremely new to Realm and so this may be a naive question, but I was wondering why the “@objc dynamic” annotation is required when Realm is used with Swift. Is it possible to do without it? Also, does it affect compatibility with running Realm on Linux or is that irrelevant?

Thank you,

(Zsolt Jandzso) #2

The @objc means that obj-c code can access to that property, that a must.

You can leave out the dynamic, but then the data reading from the db wont work - learned the hard way.
So, thats a must too.

(Nikola Irinchev) #3

Realm Swift is not compatible with Swift on Linux.

(jay) #4

At a high level, Realm is backed by old(er) ObjC code and to expose the variables (properties) you want managed to Realm, the compiler needs to know they are objc variables, hence the @objc. A bit deeper is that Objective-C runtime has some features not available in Swift and adding that attribute the compiler knows to use it.

If you want ALL off the variables in your class managed, you can leave out the `@objc’ per property and define the entire class as a managed Realm Class with

@objcMembers class DogClass {
   dynamic var dog_name = ""

Using the keyword dynamic means that the ObjC runtime decides which implementation is needed - it tells the compiler that dynamic dispatch should be used to access that property.

An example usage for the above would be the key-value observing functionality of ObjC (which isn’t available in ‘pure’ Swift) - adding @objc dynamic allows you to access that functionality for variables (properties) in Swift.