3

I have checked the related article with this problem. Issue in adding data in Realm in iOS

It seems only issue the previous post that folks were not adding dynamic to variables. that is not my case. I am not finding any other reason at all why it would fail.

Build target 12.2, swift version: Swift 5, realm version: swift-10.2.1

my class:

class Person: Object {
    dynamic var id = UUID().uuidString
    dynamic var name = "" 
}

This is how I am trying to add to the realm

    let realm = try! Realm()
    let person = Person()
    person.name = "John Doe"
    try! realm.write {
        realm.add(person)
    }

Any pointers or suggestion would be appreciated. Thanks a lot for reading the post.

Alok C
  • 2,787
  • 3
  • 25
  • 44

1 Answers1

8

You still need the @objc attribute in your variables. Also see here.

class Person: Object {
    @objc dynamic var id = UUID().uuidString
    @objc dynamic var name = "" 
}

EDIT:

For completeness, Realm Object classes can be marked as @objcMembers (Swift 4+) which will make all class properties marked with dynamic to be managed by Realm. See Property Attributes in the Swift guide.

Jay
  • 34,438
  • 18
  • 52
  • 81
Josh
  • 504
  • 3
  • 14
  • Thanks @josh, not sure how did I miss it. It was the problem. – Alok C Aug 17 '19 at 20:07
  • @Alix Be sure to [accept](https://stackoverflow.com/help/accepted-answer) this answer if is provided a solution so it can help others. – Jay Aug 18 '19 at 13:18
  • 1
    I would also like to add that *Note that if the class is declared as @objcMembers (Swift 4 or later), the individual properties can just be declared as dynamic var.* I've overlooked that several times when I see a class that just has *dymamic* in front of the vars. Keeping in mind that using *@objcMembers* will make all members with the dynamic keyword managed by Realm, which may not fit all use cases. – Jay Aug 18 '19 at 13:21