UITableView deleteRows不更新IndexPaths导致崩溃索引超出范围

时间:2020-09-10 14:07:42

标签: ios swift uitableview tableview

在成功从列表中删除项目的API调用中调用以下代码

self?.myWishlistArry?.remove(at: indexPath.row)
self?.myWishListTableView.deleteRows(at: [indexPath], with: .right)

以下是删除按钮的关闭

        myWishlistCell.closureForRemoveBtn = {
        [weak self]
        (productId, storeid) in
        self?.callAlertViewForRemoved(productid: productId, storeId: storeid, indexPath: indexPath)
    }

以下是显示警报以供用户确认的代码。

    func callAlertViewForRemoved(productid :String, storeId: String, indexPath: IndexPath) {
    
    
    let alertController = UIAlertController(title: AppLocalString.ITEM_NOT_AVAILABLE_TEXT.localized(), message: AppLocalString.MY_EXLUDE_TEXT.localized(), preferredStyle: .alert)
    
    let okAction = UIAlertAction(title: AppLocalString.ALERT_YES.localized(), style: UIAlertAction.Style.default) {
        UIAlertAction in
        if self.listBool == false {
            //self.listBool = true
            self.callRemoveWishlist(productid :productid, storeId: storeId, indexPath: indexPath)
        }
    }
    
    let cancelAction = UIAlertAction(title: AppLocalString.Cancel_ORDER.localized(), style: UIAlertAction.Style.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }
    
    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)
    
    self.present(alertController, animated: true, completion: nil)
    
    
}

以下是代码api删除

    func callRemoveWishlist(productid :String, storeId: String, indexPath: IndexPath)  {
    
    listBool = true
    addLoading(view: view, random: removeRandom)
    let addFriendsBaseUrl = AppStrings.baseUrl + AppStrings.addToWishlistAPI
    var paramDict = [String : Any]()
    
    paramDict = ["type" : "remove",
                 "productid" : productid,
                 "storeid" : "\(storeId)",
        "userid" : UserDefaults.standard.value(forKey: AppStrings.userid) ?? ""]
    
    
    let baseParams = Utility.appendBaseParams(toDict: paramDict as! [String : String])
    
    NetworkResponseManager.getDataFromUrl(url: addFriendsBaseUrl, parameters: baseParams as! [String : String] , completionHandler: {
        [weak self]
        (response, error) in
        self?.listBool = false
        if (error == nil) {
            
            if let responseDict = response {
                
                let responseDict = AddToWishlistModel(JSON(responseDict))
                self?.removeLoading(view: self?.view, random: self?.removeRandom)
                if responseDict.status == 1
                {
                    self?.myWishlistArry?.remove(at: indexPath.row)
                    self?.myWishListTableView.deleteRows(at: [indexPath], with: .right)
                } else {
                    self?.showToast(message: AppLocalString.OOPS_TEXT.localized())
                }
            }
        } else {
             self?.showToast(message: AppLocalString.OOPS_TEXT.localized())
        }
    })
}

其他表格视图代码

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


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

现在此代码首次运行,但是如果尝试删除另一个索引超出范围的项目,则会导致崩溃。考虑列表 T1,T2,T3和T4 中是否有四个项目 第一次,如果我删除T2 项目indexPath.row的值现在为1,则项目和行被删除如果我删除另一个项目,说T4 ,则 indexPath.row的值出现变成3而不是2 为什么会发生这种情况,为什么索引路径不会更新?

2 个答案:

答案 0 :(得分:1)

基于整个代码,看来问题出在Clojure

如果在cellForRowAt的clojure中调用它,则索引路径会不同(设置为在调用cellForRowAt时正确的值)。您应该根据愿望清单商品的ID进行删除(删除该商品时,商品不会改变)。

例如,创建一个像这样的方法:

  |
9 |                           (h: Nat) -> (right: RBTree p Y elem) -> RBTree {h: Nat | if X == Black && Y == Black then (S p) else p} col elem
  |                                                                            ^
unexpected ':'
expecting dependent type signature

并调用clojure func deleteWish(productId: string) { for i in myWishlistArry ?? [] { let product = myWishlistArry[i] if let product.productId == productId { myWishlistArry?.remove(at: i) myWishListTableView.deleteRows(at: [IndexPath(row: i, 0)], with: .right) } } }

答案 1 :(得分:1)

问题是在单元格顺序更改后,捕获了索引路径并且没有更新索引路径。

解决方案:

在单元格中声明闭包也通过该单元格

var closureForRemoveBtn : ((UITableViewCell, String, String) -> Void)?

并调用它

closureForRemoveBtn?(self, productId, storeId)

cellForRow中,从实际单元格

中获取索引路径
myWishlistCell.closureForRemoveBtn = {
    [weak self]
    (actualCell, productId, storeid) in
    let actualIndexPath = tableView.indexPath(for: actualCell)!
    self?.callAlertViewForRemoved(productid: productId, storeId: storeid, indexPath: actualIndexPath)
}

或更简单

var closureForRemoveBtn : ((UITableViewCell) -> Void)?

///

closureForRemoveBtn?(self)

///

myWishlistCell.closureForRemoveBtn = {
    [weak self] actualCell in
    let actualIndexPath = tableView.indexPath(for: actualCell)!
    self?.callAlertViewForRemoved(productid: actualCell.productId, storeId: actualCell.storeid, indexPath: actualIndexPath)
}