简体   繁体   中英

Swift - app crashes on TableView UIRefreshControl

When I start to update the table view (pull down to refresh), and then suddenly start flipping list, the application crashes.

fatal error: Cannot index empty buffer

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("BankCell", forIndexPath: indexPath) as BankTableViewCell

    cell.backgroundColor = UIColor(red: 241/255, green: 233/255, blue: 220/255, alpha: 1.0)

    let bank:Bank = self.allRates[indexPath.row] as Bank // <-- Error here

    cell.titleLabel.text = bank.name

    return cell
}

Probably I have to check the existence of an element in the array. But is this the right way out?

- I edit row #2:

let cell = tableView.dequeueReusableCellWithIdentifier("BankCell") as BankTableViewCell

But the error still remains.

My refresh function:

func refresh(sender:AnyObject)
{

    parser.deleteObjects()
    self.allRates.removeAll(keepCapacity: false)

    parser.parse { // - XMLParser ended to Parse file

        self.allRates = self.parser.actualBankRates + self.parser.notActualBankRates

        self.tableView.reloadData()

        self.refreshController.endRefreshing()
    }
}

In XMLParser:

var actualBankRates = [Bank]()
var notActualBankRates = [Bank]()

You forgot to register your class and therefore dequeueReusableCellWithIdentifier:forIndexPath: is unable to return the cell, eg call

tableView.registerClass(BankCell.classForCoder(), forCellReuseIdentifier: "BankCell")

when initializing your table view delegate.

Edit check, that your array allRates is initialized and filled. The error means, that it is empty.

You should ensure that your "allRates" array can be accessed at that index. Write the following code to make sure it won't crash:

if self.allRates.count > indexPath.row
{
    // Ensure you get a valid Bank returned
    if let bank = self.allRates[indexPath.row] as Bank
    {
        cell.titleLabel.text = bank.name
    }
}

You could then debug it by sticking a breakpoint on the first if statement and typing po self.allRates to check the state of your array before you tried accessing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM