写入领域数据库时崩溃

时间:2018-08-25 15:04:16

标签: ios swift realm

我有一个待办事项应用程序,正在使用领域来存储数据。我已经编写了用于写入数据库和检索的数据库代码。

当我第一次输入数据库时​​,一切正常,这就是将数据输入数据库,但是当我尝试将另一个对象输入数据库时​​,

  

由于未捕获的异常“ RLMException”而终止应用程序,原因:“尝试在写事务之外修改对象-首先在RLMRealm实例上调用beginWriteTransaction。”

func createCategory(name: String, color: String, isCompleted: Bool) -> Void {
    category.name = name
    category.color = color
    category.isCompleted = false
    DBManager.instance.addData(object: category)
}

DBManager

func addData(object: CategoryModel)   {
    try! database.write {
        database.add(object, update: true)
        print("Added new object")
    }
}

添加类别IBaction

CategoryFunctions.instance.createCategory(name: name, color: color, isCompleted: false)

2 个答案:

答案 0 :(得分:1)

.createCategory(name: name, color: color, isCompleted: false)

更改已添加对象的属性,然后尝试再次写入它,您需要创建一个新对象,也许您需要类似

func createCategory(name: String, color: String, isCompleted: Bool) -> Void {
        let category = Category()
        category.name = name
        category.color = color
        category.isCompleted = isCompleted
        DBManager.instance.addData(object: category)

        // or
        let category = Category(name:name,color:color,isCompleted:isCompleted)
        DBManager.instance.addData(object: category)

    }

答案 1 :(得分:1)

创建一个新类别:

func createCategory(name: String, color: String, isCompleted: Bool) {
    let newCategory = Category(name: name, color: color, isCompleted: isCompleted)
    DBManager.instance.addData(object: newCategory)
}