SoundShock SoundShock - 6 months ago 22
Swift Question

Realm and Objectmapper: Array of one item keeps stacking in my Realm database for every request

This is a follow-up on one of my previous questions here. I needed to map an array

types
in my Realm database, which consists of only 1 word (sometimes two), with the help of ObjectMapper.

This is the JSON:

{
"result": [
{
"id": 20,
"types": [
"now"
],
"url": "/nl/whereto/ezrhgerigerg"
},


I got the following work-around, which worked partly:

func mapping(map: Map) {
...
var typez: [String]? = nil
typez <- map["types"]

typez?.forEach { t in
let obj = getType()
obj.text = t
self.typez.append(obj)
}


And my Class of
getType()
which is an object:

class getType: Object, Mappable {
dynamic var text: String?

required convenience init?(_ map: Map) {
self.init()
}

func mapping(map: Map) {
text <- map[""]
}
}


The issue I'm having, is that every time I do a call to the backend, the database doesn't update the data in types (or deletes them, and grabs the new ones), it just keeps piling it up! This is making my getType database 280+ rows after some calls, while it is only present in 10 objects.

After x number of backend calls, this will cause a serious issue. Does anyone know what I should do?

Answer

I think you probably updated the Publication object using the primary key. Unfortunately, the getType object doesn't have a primary key. It cannot be updated automatically with the primary key.

So you can delete typez property manually if the publication object already exists. Like the following:

let publication = Mapper<Publication>().map(json)
// ...
try! realm.write {
    // Check whether the Publication object already exists
    let key = ... // Primary key value (e.g. 20)
    if let publication = realm.objectForPrimaryKey(Publication.self, key: key) {
        // If it already exists, delete `typez` objects
        realm.delete(publication.typez)
    }

    realm.add(publication, update: true)
}