【问题标题】:Save User using Realm Object使用领域对象保存用户
【发布时间】:2017-10-02 21:50:31
【问题描述】:

我正在创建一个项目。我想如果userID 已经存在,它不会添加用户。但不知何故,我的代码无法正常工作。

这是我的领域模型对象(User.swift):

import Foundation
import RealmSwift

class User: Object {

    @objc dynamic var userID = Int()
    @objc dynamic var username = ""
    @objc dynamic var full_name = ""
    @objc dynamic var myBool = Bool()

    override static func primaryKey() -> String? {
        return "userID"
    }
}

这是添加用户的按钮:

@IBAction func add(_ sender: Any) {
        let myUser = User()
        let JSON_userID = Int(arc4random_uniform(5)) // This is temporary. I am going to get code from JSON, but using random for testing purpose.

        if (myUser.userID != JSON_userID) {
            myUser.userID = JSON_userID
            myUser.username = "myUsername"
            myUser.full_name = "My Name"

            let realm = try! Realm()
            try! realm.write {
                realm.add(myUser)
            }
        }
        else {
            print("Already exist")
        }
    }

有时它会运行代码,但大多数时候它会因错误而崩溃:

libc++abi.dylib: terminating with uncaught exception of type NSException.

【问题讨论】:

  • 您必须查询数据库并针对其中的所有用户进行测试。您的 if 语句将始终为真,因为您始终使用新创建的用户进行测试。
  • 异常的信息是什么?

标签: ios swift xcode realm


【解决方案1】:

当您在User 对象中定义主键时,如果您在write 闭包内将update 参数设置为true,则Realm can handle this automatically

let realm = try! Realm()
try! realm.write {
   realm.add(myUser, update: true)
}

如果update参数未设置或false,当你尝试添加具有现有主键的对象时,Realm会抛出异常。

这使得if / else 条件无效。可以删除。

如果需要知道用户是否已经存在,可以通过主键值请求Realm:

realm.object(ofType: User.self, forPrimaryKey: JSON_userID)

如果用户不存在,结果将为nil

【讨论】:

  • 这确实有效。但是我有另一个函数,如果用户已经存在,它将更新布尔值@objc dynamic var myBool = Bool()。这段代码将如何工作?
  • 您可以在您的 Realm 上使用如下主键发出请求:realm.object(ofType: User.self, forPrimaryKey: userId) != nil。如果用户已经存在,这将返回true
  • 那么应该是这样的:oi68.tinypic.com/e7gvt1.jpg ?这仍然使它崩溃。
  • 编辑:即使我使用realm.add(myUser, update: true),它也会崩溃。
  • 好吧,如果你想这样做,你需要使用主键的值 (JSON_userID) 而不是属性的名称。但我的意思是,就架构而言,完全删除if / else 并使用realm.add(myUser, update: true) 会更安全。此外,myBool 变量对我来说不是很清楚,但如果用户已经存在于数据库中,则不应存储,因为它增加了不必要的复杂性。相反,在 Realm 上发出请求以了解对象是否存在。我用 Realm 文档的链接编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多