我有简单的表格视图。 。当我想从表格视图中删除单元格时,出现此错误。
查看控制器代码:
class FoodCategoryDetailTableViewController: UITableViewController {
var foodCategoryDetailViewModel: FoodCategoryDetailTableViewViewModelType?
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
guard let foodCategoryDetailViewModel = foodCategoryDetailViewModel else { return }
tableView.delegate = nil
tableView.dataSource = nil
foodCategoryDetailViewModel.foodsInSelectedCategory
.bind(to: tableView.rx.items(cellIdentifier: FoodCategoryDetailTableViewCell.cellIdentifier, cellType: FoodCategoryDetailTableViewCell.self))
{ row, food, cell in
cell.foodCategoryDetailCellViewModel = foodCategoryDetailViewModel.cellViewModel(forRow: row)
}.disposed(by: disposeBag)
tableView.rx.itemDeleted.subscribe({ [unowned self] indexPath in
self.foodCategoryDetailViewModel?.removeFoodFromApplication(atRow: (indexPath.element?.row)!)
self.tableView.reloadData()
}).disposed(by: disposeBag)
}
查看型号代码:
class FoodCategoryDetailTableViewViewModel: FoodCategoryDetailTableViewViewModelType {
var foodsInSelectedCategory: BehaviorRelay<[Food]>
private var foodCategoryId: Int16
func cellViewModel(forRow row: Int) -> FoodTableViewCellViewModelType? {
if let food = getFood(atRow: row) {
return FoodTableViewCellViewModel(foodModel: food)
}
return nil
}
func removeFoodFromApplication(atRow row: Int) {
if let food = getFood(atRow: row) {
var foods = foodsInSelectedCategory.value
foods.remove(at: row)
self.foodsInSelectedCategory = BehaviorRelay(value: foods)
CoreDataHelper.sharedInstance.removeFoodFromApplication(foodName: food.name!)
}
}
private func getFood(atRow row: Int) -> Food? {
let food = foodsInSelectedCategory.value[row]
return food
}
init(foodCategoryId: Int16) {
self.foodCategoryId = foodCategoryId
self.foodsInSelectedCategory = BehaviorRelay(value: CoreDataHelper.sharedInstance.fetchFoodsFromSelectedCategory(foodCategoryId: self.foodCategoryId))
}
}
我正在使用核心数据。我在函数getFood()
中遇到错误。之所以存在错误,是因为视图控制器中的row
在tableview中具有较旧的项目数。删除单元格后,不会使用新的项目(食物)计数进行更新。