Hayden Holligan Hayden Holligan - 3 months ago 15
Swift Question

Trouble understanding allObjects() in Realm

I'm making an app that uses Realm as the offline database. Problem is that when I call

Workout.allObjects()
, nothing shows up. I did some debugging and found the results below

Relevant Code

class Workout: RLMObject {
dynamic var name: String?
dynamic var exercises: RLMArray = RLMArray(objectClassName: "Exercise")
dynamic var numberOfWorkouts = 0

convenience init(name: String) {
self.init()
self.name = name
}
}


func createWorkoutObject() {
let realm = RLMRealm.defaultRealm()
try! realm.transactionWithBlock {
workout = Workout()
}
}


At the end of
createWorkoutObject()
(with a breakpoint), I ran
enter image description here

So there is obviously a Workout object, but
Workout.allObjects()
doesn't seem to see it.

Why is this? I'm struggling to understand what I'm doing wrong.

Answer

The allObjects() method only returns objects that are managed by the given Realm. In createWorkoutObject() you create an instance of Workout, but do not add it to the Realm. Since this new object is not managed by the Realm, allObjects() will not return it.

Try:

func createWorkoutObject() {
    let realm = RLMRealm.defaultRealm()
    try! realm.transactionWithBlock {
        workout = Workout()
        realm.addObject(workout)
    }
}