Update all objects in a ForEach(in:) in loop


#1

Hello,

I need help about a look simple trouble.

I’ve got a class called MyObject and I want to manage a MyObject property called “selected” (Bool).

My MyObject class include a function called select() wich have to change the value of the current MyObject (Self) to True, and change the property to False for all the others MyObjects.

For that I created the function :

func select() {
        let realm = try! Realm()
        let myObjectsArray = realm.objects(MyObject.self)
        for myObject in myObjectsArray {
            try! realm.write {
                myObject.selected = false
            }
        }
        self.selected = true
    }

But if I check into Realm Studio, the value doesn’t change. In the debugging, myObjectsArray retrieve the good number of myObject, but the id (Primary Key) is not the id of my MyObjects.

Any idea ?

Thanks a lot :slight_smile:


#2

First of all, dont use

try! realm.write { 

}

Secondly, the

let realm = try! Realm()

makes a new realm object. Did you set the default realm as a synced realm?


#3

Sorry for the late answer…

Why don’t use try! realm.write ?
I thunk that it’s the only way to save persistant data. Without that, I have an error message that I try to save data without using a write instruction.

I set my real data model for using a Primakey, that’s what you mean ? I’m using RealDatabase (localy)

Thanks for your help


#4

I meant that you shouldn’t use force try, you should always catch the error. It’s an IO function, a lot of things can go wrong.

Also, can you post the MyObject model?


#5

Also - do you want to change this objects selected property to true in Realm or just on the object?

If it’s a managed property it should only be updated within a write, so if you want to save it in Realm, that needs to be in your write as well.