Swift - 应用在 TableView UIRefreshControl 上崩溃

Swift - app crashes on TableView UIRefreshControl

当我开始更新 table 视图(下拉刷新),然后突然开始翻转列表时,应用程序崩溃。

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
}

可能我必须检查数组中是否存在某个元素。但这是正确的出路吗?

- 我编辑第 2 行:

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

但错误依旧。

我的刷新功能:

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()
    }
}

在 XMLParser 中:

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

您忘记注册 class,因此 dequeueReusableCellWithIdentifier:forIndexPath: 无法 return 单元格,例如打电话

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

在初始化您的 table 视图委托时。

编辑 检查您的数组 allRates 是否已初始化并填充。错误意味着它是空的。

您应该确保可以在该索引处访问您的 "allRates" 数组。编写以下代码以确保它不会崩溃:

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
    }
}

然后您可以通过在第一个 if 语句上放置一个断点并在尝试访问它之前键入 po self.allRates 来检查数组的状态来调试它。