Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

ios - "Attempt to delete row from section 1, but there are only 1 sections before update"

I'm trying to delete the rows that don't meet the criteria in the for loop. However, I'm getting and error that says: 'attempt to delete row 0 from section 1, but there are only 1 sections before the update." I'v never seen this before and not sure why I am getting it.

My code:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = theTableView.dequeueReusableCellWithIdentifier("MyCell") as! TableViewCell
    cell.titleLabel.text = titles[indexPath.row]
    cell.priceLabel.text = prices[indexPath.row]
    cell.descLabel.text = descs[indexPath.row]
    cell.itemImage.image = itemImages[indexPath.row]
    cell.userNumber = phoneNumbers[indexPath.row] as! String
    cell.timeLabel.text = datesHours[indexPath.row]! + "hr"
    cell.distanceLabel.text = String(locations[indexPath.row]!) + "mi"
    cell.viewController = self




    self.theTableView.beginUpdates()

    for (index, number) in self.locations {
        if number <= 5 {
            let indexPath = NSIndexPath(forRow: number, inSection: 1)
            self.theTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        }
    }
    self.theTableView.endUpdates()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems like you are telling the table there will be more rows than you actually want to display and then deleting them after the fact.

Instead you should be checking if the elements in the array meet the criteria in (or before) numberOfRowsInSection and putting them into a different array that will actually be displayed so that the table knows how many rows will actually be displayed. Then in cellForRowAtIndexPath just use the newly create array that has the data that will actually be displayed.

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.

        self.displayArray = []
        for (index, number) in self.locations {
            if number <= 5 {
               self.displayArray.Add(self.locations[index])
            }
        }
        return self.displayArray.Count
    }

I'm assuming your error has something to do with you trying to update the table in a method that is first trying to create it. You're trying to update something that hasn't fully been created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...