realm-cocoa save an empty object rather than object I passed

30 views Asked by At

I met a problem in realm-cocoa 2.8.0(in 2.7.0 it works good) which is when I want to save an object into the realm file, I saw an empty object with default value is saved into the realm rather than the object I created(even the primary key is different.) Eg.

class XXXRealmObject: RLMObject {
  @objc dynamic var id: String = UUID().uuidString.lowercased()
  @objc dynamic var name: String = ""

  @objc init(name: String) {
    self.name = name
    super.init()
  }

  @objc override init() {
    super.init()
  }

  override class func primaryKey() -> String {
    return "id"
  }
}

let obj = XXXRealmObject(name: "jojo")
let realm = try! RLMRealm(configuration: .default())
try? realm.transaction {
    *breakpoint*
    realm.addOrUpdate(object)
}

I add a before realm.addOrUpdate(object) and print the object, it show correct object, but after realm.addOrUpdate(object) get executed, in realm file, I can only see an object

{
    id: 169e6bc2-9b34-44ae-8ac3-70e6b9145adc,
    name: ""
}

and the id is also different from what I saw in break point. It looks like Realm create an object rather use the object I passed in. I am asking for some help here.

So what will cause realm create an empty object(maybe default value?) rather than save the object I passed. I just want to get some possible reasons here.

1

There are 1 answers

0
Xin Guo On

I think I got it, in my project, we have a category for NSObject which include a method called objectForKey, and in Realm's src, when we read value from RLMObject, we check if it can response to objectForKey, normally it should return false and keep executing following code to get the real value, but in my project, the code will return nil because it's not a dictionary.

So will close this