MohamMad Salah
MohamMad Salah

Reputation: 981

Can not add objects from a different Realm iOS & Swift

In my app I am managing multiple realm databases files, that's it, for each logged in user a realm file (.realm) exists.

So when the user login to the app I am doing the following:

class func setDefaultsForLocationId(_ userId: String) {
    var config = RealmManager.realmConfiguration()
    // Use the default directory, but replace the filename with the business id
    config.fileURL = config.fileURL!.deletingLastPathComponent()
        .appendingPathComponent("\(userId).realm")
    // Set this as the configuration used for the default Realm
    Realm.Configuration.defaultConfiguration = config
}

once that done I start to add to realm using:

fileprivate func storeTransaction(_ student: Student) -> Bool {
    let realm = try! Realm()
    var retVal = true
    do {
        try realm.write {
            realm.add(student, update: true)
        }
    } catch {
        retVal = false
    }
    return retVal
}

that will work fine until the current user logout and a new one logged in it will throw an exception : Can not add objects from a different Realm.

Note 1: I am using only one realm instance at a time not multiple instances from different .realm files at the same time.

Note 2: I found out that if I am logout and login using the same account; the exception will not appear, only if I use different accounts!

Upvotes: 1

Views: 781

Answers (1)

kishikawa katsumi
kishikawa katsumi

Reputation: 10573

In general, adding objects from a different Realm is considered to be a bug. There is no point in separating files if objects are mixed. Therefore, when switching Realm files you should destroy or reload objects belonging to the previous Realm yourself.

If that is an intentional behavior, there is a way to avoid exceptions by detaching Student objects from Realm as follows.

fileprivate func storeTransaction(_ student: Student) -> Bool {
    let detachedStudent = Student(value: student)
    ...
        realm.add(detachedStudent)
    ...

Upvotes: 2

Related Questions