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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With