【发布时间】:2021-10-30 12:01:44
【问题描述】:
您好,我正在尝试使用以下代码从领域中名为“book”的对象更改变量“category”:
alert.addAction(UIAlertAction(title: "Reading", style: .default, handler: { (_) in
try! realm.write {
let category = "reading"
let book = Book()
book.category = category
}
}
当我签入 mangoDB realm studio 时,对象类别尚未更新。我看过的教程使用了相同的功能。这是整个更新的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
func showmethisfunction() {
let realm = try! Realm()
let boook = Book()
let alert = UIAlertController(title: "Want to put your book in a list?", message: "Please Select an Option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Read", style: .default, handler: { (_) in
try! realm.write
{
boook.category = "read"
}
}))
alert.addAction(UIAlertAction(title: "Want to read", style: .default, handler: { (_) in
try! realm.write {
boook.category = "wanttoread"
}
}))
alert.addAction(UIAlertAction(title: "Reading", style: .default, handler: { (_) in
try! realm.write {
let category = "reading"
boook.category = category
}
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in
print("User click Dismiss button")
}))
self.present(alert, animated: true, completion: {
print("completion block")
})
}
showmethisfunction()
}
我使用了一个类似的警报控制器手动添加一本书,这很有效,但当我想从书中添加变量时它就不起作用了
【问题讨论】:
-
您问题中的代码非常正确。我的猜测是您使用 Realm Studio 打开了错误的 .realm 文件,因此您看不到更新。此外,问题
boook和book中有两个不同的变量,这可能会导致混淆。当您这样做let book = Book()时,它将创建一个全新的图书对象,而不是更新现有的。 -
该代码实际上应该更新现有变量,因为它是在我点击 tableview cel 时触发的。我也用我的分段控件尝试了这个,但它不起作用,我如何将代码更改为更新现有书籍?
-
如果我的评论正确,我必须使用:let book = realm.objects(Book.self)。但随后我收到以下错误“结果
”类型的值没有成员“类别” -
嗯,是的,也不是。此代码
let book = realm.objects(Book.self)不读取书籍对象 - 变量最好表示为bookResults,因为它将读取所有书籍对象。您收到的错误是因为 Results 对象没有category参数 - 只有一个 book 对象具有该属性。我会添加一个答案。