Search code examples
swiftrealm

Can @Persisted property be also @objc in Realm


Realm database offers, since version 10.10.0, to declare stored properties with @Persisted annotation, replacing the @objc dynamic annotation.

The documentation is pretty clear about the transition: mixing has serious consequences.

If you mix @Persisted and @objc dynamic property declarations within a class definition, any property attributes marked as @objc dynamic will be ignored.

But I can't find any information about a property that would be annotated with @Persisted @objc, for properties that are accessed from Objective-C code, or for the simplicity of getting a String out of a #keyPath.

So for example, would both these properties would get persisted?

@Persisted var token: String?

@Persisted @objc var lastRegisteredDate: Date?

Edit: Here's an example of a compiling error with a Swift property marked with @Persisted that is accessed from some objective-c code.

Model:

@objc
public class PushNotificationSettings: Object {

    @Persisted
    public var registrationId: String?
}

Objective-c code:

// declaration of a property to be used in a block. 
// The compiler will complain that "Property 'registrationId' not found on object of type 'PushNotificationSettings *'"
__block NSString *registrationId = self.settings.registrationId;

Solution

  • So for example, would both these properties would get persisted?

    Yes. Taking the code in the question and adding it to a Realm object:

    class Test: Object {
        @Persisted var token: String?
        @Persisted @objc var lastRegisteredDate: Date?
    }
    

    and then writing it to Realm

    let t = A_Test()
    t.token = "Hello, World"
    t.lastRegisteredDate = Date()
    
    try! realm.write {
        realm.add(t)
    }
    

    results in both properties being populated and persisted

    enter image description here