Swift 3: Realm creates an additional object instead of updating an existing 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 a user only when there are no user objects in the application.

thanks to this answer I am updating my object as follows

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

But it turns out that he creates a new User object. How to always update an existing one, and not create a new object?

Please note that I am using User.current, since my object is singleton

After logging in and logging out, it prints the number of users = 2, which means that updating an existing user creates a new

+4
source share
2 answers

realm.write , realm.add . 2 , , , , , .

realm.add 2 , , 2 User .

, , , Realm .

let realm = try! Realm()
let firstUser = realm.objects(User.self).first

if let firstUser = firstUser {
    User.current.setFromRealm(user: firstUser)
    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) }
}
+1

Realm , . add update.

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

:

 - 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.
+6

Source: https://habr.com/ru/post/1668241/


All Articles