I have a live (working) version of an iOS app (swift 3) which uses Realm Swift (2.4.2) for storage and offline use. I'm using simple tables as structures with primary key and (yet) no relationships at all. Everything was working perfect, until the moment I realized that calling below snippet::
entities = fetch from web...... // pseudo
let realm = try Realm()
try realm.write {
realm.add(entities, update: true)
}
- Successfully adds entities(rows) that didn't exist in db before (based on primary key).
- Updates existing rows(based on primary key again) that exist in db.
- WILL NOT delete rows that use to exist in db but do not anymore (based on primary key).
Declaration of primary key::
override static func primaryKey() -> String? {
return "ID"
}
where "ID" is the Class' primary key attribute as per realm doc.
Anyway as a workaround I was nuking (drop) whole table before updating::
entities = fetch from web...... // pseudo
let realm = try Realm()
let storedObjects = realm.objects(Entity.self)
try realm.write {
realm.delete(storedObjects) // nuke entities
realm.add(entities)
}
but I am pretty sure there must be must be a better way.
I' ve found a similar thread in StackOverflow in the past, but proposed solutions are workarounds pretty much like my own. This is not what I' m looking for...