App尝试使用Realm时崩溃SIGABRT

时间:2016-06-25 20:33:03

标签: ios xcode swift realm

我正在尝试使用Realm保存一个简单的对象,但是当尝试进行写入事务时,应用程序仍然会崩溃,即使它被包装在Do Catch块中也是如此。

let theme = Theme()
    theme.name = "Custom Theme"
    theme.backgroundColor = backgroundColor
    theme.accentColor = accentColor
    theme.numberColor = numColor
    theme.functionColor = funcColor

    // Add to the Realm inside a transaction
    do {
        try Realm().write {
            do {
                try Realm().add(theme, update: true)
            } catch {
                print("Error saving data")
            }
        }
    } catch {
        print("Realm.write error")
    }

这是“主题”对象

class Theme : Object {
dynamic var name = ""
dynamic var backgroundColor = ""
dynamic var accentColor = ""
dynamic var numberColor = ""
dynamic var functionColor = ""

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

}

这是崩溃的截图 SIGABRT Crash

编辑:导致崩溃的上述代码仅在单击按钮时执行。也没有控制台输出。我通过CocoaPods带来了领域。

1 个答案:

答案 0 :(得分:1)

啊,它可能与你创建领域实例的方式有关,试试这个:

let realm = try! Realm()

do {
    try realm.write {
        do {
            try realm.add(theme, update: true)
        } catch {
            print("Error saving data")
        }
    }
} catch {
    print("Realm.write error")
}

但是,通常您不需要将事务包装到do-catch块中:

let realm = try! Realm()

try! realm.write {
    realm.add(theme, update: true)
}