ios - 如何使用 UITableView - Swift 从 Realm 中删除对象

标签 ios swift uitableview realm

通过 UITableViewRealm 中删除对象的最常见方式(代码结构)是什么?

以下代码可以很好地在 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)
    }
}

同样,通过 UITableViewRealm 中删除对象的最常见方法是什么?

谢谢

最佳答案

为简洁起见省略了一些解包和捕获逻辑

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/

相关文章:

ios - 如何从调用方法的 NSInvocationOperation 获取对象?

ios - 将 UINavigationController 转换为图像使 UINavigationBar 半透明

ios - Swift SearchResultsController Segue - "Receiver ... has no segue with identifier ' testSeg ''"

ios - 自定义 UITableViewCell 中的 UIScrollView 混合数据

objective-c - 标签栏项目标题以编程方式未显示在 objective-c 中

iphone 应用程序 : cannot retrieve property from a Custom Singleton

swift - RxSwift 中多节表格 View 的 ViewModel 输入和输出

ios - 通过委托(delegate)选择 TableView 行是选择多行而不是一行

ios - NSMutableArray removeObjectAtIndex 在第二次执行时崩溃

ios - 删除标题后如何删除 UITableView 标题上的空白区域?