【问题标题】:Swift 3: Realm creates additional object instead of updating the exisiting oneSwift 3:Realm 创建额外的对象而不是更新现有的对象
【发布时间】:2017-01-30 10:18:24
【问题描述】:

在我的 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) }
    }

我只在应用程序中没有用户对象时才创建用户

感谢answer 我通过以下方式更新我的对象

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

但事实证明它创建了新的用户对象。如何始终更新已经存在的对象而不是创建新对象?

请注意,我使用 User.current,因为我的对象是单例

在我登录和注销后,它会打印用户数 = 2,这意味着更新现有用户会创建一个新用户

【问题讨论】:

    标签: ios swift swift3 realm


    【解决方案1】:

    Realm 将为您检查对象是否存在。仅使用addupdate

    // 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.
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我确实在我以前的 db 相关类管理器​​的其他地方添加了对象,我设法自己修复了它,但我仍然认为这个答案值得接受 :)
      猜你喜欢
      • 2017-02-25
      • 2019-03-12
      • 2015-02-02
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多