Swift 3:Realm创建其他对象,而不是更新现有对象 [英] Swift 3: Realm creates additional object instead of updating the exisiting one

查看:66
本文介绍了Swift 3:Realm创建其他对象,而不是更新现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的AppDelegate中

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

感谢此 answer 我以以下方式更新对象

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)
}

但是事实证明,它创建了新的User对象.如何总是更新已经存在的对象而不是创建新对象?

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

请注意,由于我的对象是单身人士,因此我使用User.current

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

登录并注销后,它显示的用户数= 2,这意味着更新现有用户会创建一个新用户.

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

推荐答案

realm.write无法添加新对象,除非您在其中调用realm.add.如果在数据库中有2个对象,则意味着检查对象是否已存在的逻辑失败,或者注销时删除前一个对象的逻辑失败.

realm.write is incapable of adding new objects, unless you're calling realm.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.

在同一对象上调用两次realm.add不会将2个副本添加到数据库中,因此也可能表明您也在逻辑中创建2个非托管User对象.

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 unmanaged User objects in your logic as well.

无论如何,我建议您仔细检查一下您的逻辑,以确保您不会偶然将两个对象添加到Realm中.

In any case, I'd recommend double-checking your logic to absolutely ensure you're not adding two objects to Realm by accident.

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) }
}

这篇关于Swift 3:Realm创建其他对象,而不是更新现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆