首页 > 解决方案 > 尝试在领域中编辑列表

问题描述

我正在尝试List使用领域:

class TripsList : Object {
    let trips = List<Trip>()
}

然后,在我的 ViewController 类中:

var trips : Results<TripsList>?

override func viewDidLoad() {
    super.viewDidLoad()

    trips = realm.objects(TripsList.self)

}

当有人移动 UITableViewRow 时,我想更新我的领域数据库。

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedObject = self.realm.objects(Trip.self)[sourceIndexPath.row]

    trips.remove(at: sourceIndexPath.row)
    trips.insert(movedObject, at: destinationIndexPath.row)

}

这是我的 TableView 数据源方法:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return realm.objects(Trip.self).count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.font = UIFont.systemFont(ofSize: 17)
    cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
    cell.textLabel?.text = nameData.names[realm.objects(Trip.self)[indexPath.row].tripID]
    return cell
}

问题是没有选项可以做trips.remove(at:)trips.insert(_:at:)

我的总体目标是能够在有人移动 UITableViewRow 并更新我的领域数据库时插入和删除。

标签: swiftrealmrealm-list

解决方案


您不能直接修改Results实例。Results是自动更新集合,这意味着它们始终反映您用于初始化它们的查询的当前状态。您需要修改Realm才能修改Results实例。

此外,Results只有在您对其进行排序时,才能保证实例保持其排序。因此,您需要引入一个属性Trip,用于对对象进行排序并在用户移动一行时修改该属性。

您的TripsList类似乎是不必要的,因为您似乎只是想Trip在 Realm 中存储许多对象,然后在没有实际进行任何分组的情况下检索它们。即使您需要对它们进行分组,也可以使用 Realm 查询来实现。记住这一点,这就是我修改当前代码以允许用户对其Trips 进行排序并将排序保存到Realm.

class Trip: Object {
    // Your existing code for Trip 
    ...
    // Sorting property
    @objc dynamic var sortingIndex = 0
}

在您的表视图控制器中:

var trips : Results<Trip>?

override func viewDidLoad() {
    super.viewDidLoad()

    trips = realm.objects(Trip.self).sorted(byKeyPath: "sortingIndex")
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return trips?.count ?? 0
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.font = UIFont.systemFont(ofSize: 17)
    cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
    if let tripID = trips?[indexPath.row].tripID {
        cell.textLabel?.text = nameData.names[tripID]
    }
    return cell
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    guard let movedObject = trips?.[sourceIndexPath.row] else { return }
    // Depending on your exact needs, you might want to update the `sortingIndex` property of your other rows as well, whose position in the table view was affected by the reordering
    try! realm.write {
        movedObject.sortingIndex = destinationIndexPath.row
    }
}

推荐阅读