Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Realm creates additional object instead of updating the exisiting one

In my AppDelegate

let realm = try! Realm()
    print("number of users")
    print(realm.objects(User.self).count)
    if !realm.objects(User.self).isEmpty{
        if realm.objects(User.self).first!.isLogged {
            User.current.setFromRealm(user: realm.objects(User.self).first!)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let viewController = storyboard.instantiateViewController(withIdentifier :"TabBar") as! CustomTabBarController
            self.window?.rootViewController = viewController
        }
    } else {
        try! realm.write { realm.add(User.current) }
    }

I create user only when there are no user objects across the app

thanks to this answer I update my object in the following way

public func update(_ block: (() -> Void)) {
    let realm = try! Realm()
    try! realm.write(block)
}

But it turns out it creates new User object. How to always update the already existing one instead of creating new object?

Note that I use User.current since my object is a singleton

After I login and logout, it prints number of users = 2, which means that updating already existing user creates a new one

like image 616
theDC Avatar asked Jan 04 '23 15:01

theDC


1 Answers

Realm will check if the object exist or not for you. Only use add and update.

// Create or update the object
try? realm.write {
   realm.add(self, update: true)
}     

Documentation :

 - parameter object: The object to be added to this Realm.
 - parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
                     key), and update it. Otherwise, the object will be added.
like image 148
Jordan Montel Avatar answered Jan 17 '23 18:01

Jordan Montel