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
Realm will check if the object exist or not for you. Only use
add
andupdate
.Documentation :
realm.write
is incapable of adding new objects, unless you're callingrealm.add
inside of it. If you're getting 2 objects in the database, it either means that your logic for checking if the object already exists is failing, or the logic for deleting the previous object when logging out is failing.Calling
realm.add
on the same object twice will not add 2 copies to the database, so it could also indicate you're creating 2 unmanagedUser
objects in your logic as well.In any case, I'd recommend double-checking your logic to absolutely ensure you're not adding two objects to Realm by accident.