Im getting a JSON file from the api with versions of different api links so that i will know which information to download again if it is outdated.
I have a Version class which looks like this:
class Version : Object {
dynamic var myKey = NSUUID().uuidString
dynamic var banks_v = 0
dynamic var atms_v = 0
override static func primaryKey() -> String? {
return "myKey"
}
My idea is to take an old version from realm and to download the new version from api and if the versions dont match I should download the JSON file that I need and update my realm. Im doing it like this:
let newVersion = Version()
for item in json {
newVersion.banks_v = item.1["banks_v"].intValue
newVersion.atms_v = item.1["atms_v"].intValue
}
// ---- NEED HELP HERE START
let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: newVersion.myKey)
// NEED HELP HERE END ----
var rewriteVersion = false
if newVersion.banks_v != oldVersion?.banks_v {
print(newVersion.banks_v) // prints 3 (correct)
print(oldVersion?.banks_v) // prints nil (???)
self.getBanks()
rewriteVersion = true
}
if newVersion.atms_v != oldVersion?.atms_v {
self.getAtms()
rewriteVersion = true
}
if rewriteVersion {
try! self.realm.write {
self.realm.add(newVersion, update: true)
}
}
The problem is that I don't know how to properly get the object from realm. I think this part is wrong:
forPrimaryKey: newVersion.myKey
I also tried putting "myKey" there but it is still nil. Any ideas on this?
Thanks in advance!
I fixed it!
In my model class I replaced my id like this:
dynamic var id = 0
and here:
let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: 0)