多次调用deleteRowsAtIndexPaths

时间:2016-03-27 12:03:14

标签: ios swift uitableview

关于这个问题有几个问题。我已经尝试了所有建议的答案,但还没有任何工作。 所以我有这个func拒绝用户收到的优惠。我可以拒绝优惠并删除单元格行,但当只剩下一个单元格时,我会得到fatal error: Index out of range

func declineButtonTapped(sender: AnyObject) {
    self.view.userInteractionEnabled = false
    let buttonRow = sender.tag  // this is the tag from my custom cell button
    let offer = offers[buttonRow]  // I get the error here 
    let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    loadingNotification.mode = MBProgressHUDMode.Indeterminate
    loadingNotification.labelText = "declining offer...."
    let myUrl = NSURL(string: "\(ipAddress)/api/v1.0/offers.php")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let postString = "id=\(offer.id!)&action=decline&offer_id=\(offer.offer_id!)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
        { data, response, error in

            if error != nil {

                let messageToDisplay = error                    
                self.view.userInteractionEnabled = true

                return

            }


            do{
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                if let parseJSON = json{

                    let resultValue = parseJSON["status"] as? String

                       if resultValue == "Success"{


                          dispatch_async(dispatch_get_main_queue()) {

                            print("before count is \(self.offers.count)") // before the error the count is 2 here
                            self.offers.removeAtIndex(buttonRow) //update my model
                            self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: buttonRow, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
                            print("after count is \(self.offers.count)") //then the count is 1 here      
                            MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

                            self.view.userInteractionEnabled = true

                        }


                     }else{

                        //no success    
                }
             }


         } catch{

      }

  }

    task.resume()

}

cellForRowAtIndexPath内我指定按钮的标记值

offerCell.declineButton.tag = indexPath.row
offerCell.declineButton.addTarget(self, action: #selector(OpenDealsDetailsViewController.declineButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)

****** ***** UPDATE

我想我发现了错误。当我打印 print("button row is\(buttonRow)")号码不会更新。所以它第一次调用正确的行,但第二次保留了indexPath.row,它是第一次调用declineButtonTapped

button row is0 before count is 2 after count is 1 button row is1 // this of course should be 0 as there is only one cell left fatal error: Index out of range

如果我尝试

self.offers.removeAtIndex(buttonRow)                                
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: buttonRow, inSection:   0)], withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.reloadData()

我收到以下错误:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

1 个答案:

答案 0 :(得分:1)

您要么不应该使用标签,要么在每次更改后重新加载表格视图。或者,您可以迭代可见单元格并更新其标记值。

如果你总是只删除表格中的最后一行,那就没事了。一旦删除了前一行,之后的所有行现在都有不正确的标记值。因此,当您转到最后一行时,它实际上并不存在于该标记处,而任何其他无效行将导致您从服务器中删除错误的项目。

更好的方法是向单元格传递一个类的实例,该类可以执行删除操作,并使用所做更新的详细信息回调到视图控制器。然后,视图控制器可以更新其数据源和表视图。通过这种方式,您可以将表索引路径与您要对数据执行的操作分开。

相关问题