Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RLMException attempting to create object with an existing primary key after check

Tags:

ios

swift

realm

I'm receiving an RLMException for the following reason:

Attempting to create an object of type 'Student' with an existing primary key value '258975085-504336622-62850'.

The confusing part is that it's occurring just after a check that there are no existing objects with this key in the Realm.

let realm = try Realm()
if let info = realm.object(ofType: Student.self, forPrimaryKey: newStudent.userId) {
    try realm.write {
        info.name = newStudent.name
        info.school = newStudent.school
        info.email = newStudent.email
    }
}
else {
    try realm.write {
        realm.add(newStudent) //RLMException occurs here
    }
}

This code is all running asynchronously on the GCD utility queue, inside a do/catch block. It's triggered by a button in the user interface, but nothing else is accessing realm at the same time.

Why could that if statement allow the else code to run?

like image 225
Andy Avatar asked Feb 28 '18 09:02

Andy


2 Answers

In my case, I added condition to check whenever new user logs in:

if newStudent == nil{
     self.realm.add(newStudent, update: .all)
}
like image 129
Abdul Karim Khan Avatar answered Nov 04 '22 09:11

Abdul Karim Khan


try! self.realm.write {
    self.realm.add(newStudent, update: true)
}

You're adding same Object (student) with existing primary key. So you can just update current one. Instead of deleting and adding new one.

like image 4
Ignelio Avatar answered Nov 04 '22 10:11

Ignelio