通过 UITableView
从 Realm
中删除对象的最常见方式(代码结构)是什么?
以下代码可以很好地在 UITableView 中显示来自 Realm
的数据,但如果我需要删除一行并更新 Realm
,因为 Results
没有 remove
方法。
我是否需要将我的对象放入 List
中并通过它进行删除?如果这是最常见的方法,我不太确定如何使 Realm
中的“List”和 Results
保持同步。
模型类
import RealmSwift
class Item:Object {
dynamic var productName = ""
}
主视图 Controller
let realm = try! Realm()
var items : Results<Item>?
var item:Item?
override func viewDidLoad() {
super.viewDidLoad()
self.items = realm.objects(Item.self)
}
func addNewItem(){
item = Item(value: ["productName": productNameField.text!])
// Save to Realm
try! realm.write {
realm.add(item!)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath)
let data = self.items![indexPath.row]
cell.textLabel?.text = data.productName
return cell
}
删除行
从 UITableView
中删除行的标准方法在这种情况下当然不起作用,因为我使用的是来自 Realm 的默认 Results
容器。
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete{
items!.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
同样,通过 UITableView
从 Realm
中删除对象的最常见方法是什么?
谢谢
最佳答案
为简洁起见省略了一些解包和捕获逻辑
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete{
if let item = items?[indexPath.row] {
try! realm.write {
realm.delete(item)
}
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
}
关于ios - 如何使用 UITableView - Swift 从 Realm 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451784/