【发布时间】:2017-04-17 12:45:12
【问题描述】:
通过UITableView 从Realm 删除对象的最常见方式(代码结构)是什么?
以下代码可以很好地在 UITableView 中显示来自 Realm 的数据,但如果我需要删除一行并更新 Realm 则不能,因为 Results 没有 remove 方法。
我是否需要将我的对象放入List 并通过它进行删除?如果这是最常用的方法,我不太确定如何让来自Realm 的“列表”和Results 保持同步。
模型类
import RealmSwift
class Item:Object {
dynamic var productName = ""
}
主视图控制器
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)
}
}
同样,从Realm 到UITableView 删除对象的最常用方法是什么?
谢谢
【问题讨论】:
标签: ios swift uitableview realm