I've an issue between Realm and Object mapper, I tried to get a JSON from an User instance but things I've tried doesn't work and I'm not updating the object. From ObjectMapper documentation I've seen:
Note: Generating a JSON string of a Realm Object using ObjectMappers' toJSON function only works within a Realm write transaction.
I've tried to call toJSON within or without a write block but it trigger the following exception:
* Terminating app due to uncaught exception 'RLMException', reason: 'Primary key can't be changed after an object is inserted.
My try:
public func toJSONDictionary(removeCollections: Bool = false, completion: (_ result: [String: Any]?) -> Void) {
do {
try UserManager.realm?.write {
var JSON = self.toJSON() // Line causes the exception
if removeCollections == true {
JSON.removeValue(forKey: "children")
JSON.removeValue(forKey: "role")
JSON.removeValue(forKey: "godparents")
JSON.removeValue(forKey: "pending_godparents")
JSON.removeValue(forKey: "pictures")
}
return completion(JSON)
}
} catch {
return completion(nil)
}
}
I believe this is happening because in the mapping function you are mapping to your primary key directly using <-. This operator has an inout flag for the left hand parameter which makes Realm believe we are modifying it. Since Realm doesn't allow any modification of your primary key you may want to use the >>> to get around the issue. The >>> only handles writing to JSON and doesn't use the inout flag. So your solution could look something like the following:
func mapping(map: Map){
if map.mappingType == .fromJSON {
primaryKey <- map["primaryKey"]
} else {
primaryKey >>> map["primaryKey"]
}
}
Most helpful comment
I believe this is happening because in the mapping function you are mapping to your primary key directly using
<-. This operator has aninoutflag for the left hand parameter which makes Realm believe we are modifying it. Since Realm doesn't allow any modification of your primary key you may want to use the>>>to get around the issue. The>>>only handles writing to JSON and doesn't use theinoutflag. So your solution could look something like the following: