Swift - 从领域中的模型中删除值

时间:2017-07-10 07:52:33

标签: ios button swift3 realm

我尝试使用realmswift3删除对象。当用户使用google登录时,userinfos将存储在realm db中。现在我想删除用户,当我点击一个按钮。

这是我未完成的代码:

@IBAction func deleteUser(_ sender: Any) {

    let realm = try! Realm()
    let userObject = realm.objects(userInfos.self).filter("id == 0").first
    realm.delete(userObject)
    try! realm.write

    print("deleted")
    print(userObject)
}

上面的代码不起作用。有什么问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试:

let realm = try! Realm()
if let userObject = realm.objects(userInfos.self).filter("id == 0").first {
    print("User is existed, it's being deleted.")
    try! realm.write {
         realm.delete(userObject)
    }
    print("Deleted.")
}
else{
    print("User is not found.")
}