Realm不能使用Xcode 9.2工作SIGNAL SIGABRT

时间:2018-01-25 11:53:59

标签: ios swift realm

我使用Xcode 9.2和swift 4作为IOS应用程序 一切都很好,但是当我添加领域[点击按钮后保存到数据库],然后单击按钮,应用程序粉碎此消息

SIGNAL SIGABRT 

当我用

的简单方法改变了领域方法
print("clicked")

它有效

我使用此pod行添加库

pod 'RealmSwift'

我有以下代码

 floaty.addItem("Share", icon: UIImage(named: "share-variant")! , handler:{ item in
        self.shareTxt()
    })
    floaty.addItem("Save", icon: UIImage(named: "content-save")! , handler:{ item in
        self.saveToDB()
    })
func saveToDB() {
    let realm = try! Realm()
    realm.beginWrite()
    realm.create(News.self, value: [SingleItem?.id])
    try! realm.commitWrite()

}
class News: Object {
@objc dynamic var new_id = ""
}

1 个答案:

答案 0 :(得分:0)

首先,将属性new_id设为主键:

class News: Object {
    @objc dynamic var new_id = ""

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

然后,添加或更新模型:

func saveToDB() {
    if let newId = SingleItem?.id {
        let realm = try! Realm()
        let news = realm.objects(News.self).filter("new_id == \(newId)").first

        if news != nil {
           try! realm.write {
               //optional, updating some fields...
               //like: news.title = "some title"
           }
        }
        else{
           let news = News(value: ["new_id", newId])
           try! realm.write {
               realm.add(news)
           }
        }
    }
}