【问题标题】:self.tableView.reloadData() not workingself.tableView.reloadData() 不工作
【发布时间】:2015-09-16 15:14:54
【问题描述】:

我知道有数以千计的 tableView.reloadData() 问题有答案,但没有一个对我有用!有人可以告诉我如何正确重新加载数据吗?很难解释我的问题,所以我将向您展示我的代码。 这是我的整个文件:

import UIKit
import Foundation
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var amountField: UITextField!
    @IBOutlet weak var whoPaysLabel: UILabel!
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var datePicker: UIDatePicker!

    var names:NSMutableArray = []
    var amounts:NSMutableArray = []
    var dates:NSMutableArray = []
    var whoPays:NSMutableArray = []
    var status:NSMutableArray = []
    var arrayNumber:Int = -1

    @IBOutlet weak var tableView: UITableView!

    let textCellIdentifier = "EntityCell"
    var entityCellArray:[String] = []

    let newDate = NSDate()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func changeWhoPays(sender: UISwitch) {
        if(sender.on){
            whoPaysLabel.text = "\(nameField.text) pays you"
        }else{
            whoPaysLabel.text = "you pay \(nameField.text)"
        }
    }

    @IBAction func changeStatus(sender: UISwitch) {
        if sender.on{
            statusLabel.text = "paid"
        }else{
            statusLabel.text = "not paid"
        }
    }

    func createNewEntity(){
        names.addObject(nameField.text)
        if let amountField_ = amountField.text.toInt() {
        amounts.addObject(amountField_)
        }
        dates.addObject(datePicker.date)
        if whoPaysLabel.text == "\(nameField.text) pays you"{
            whoPays.addObject("they pay")
        }else{
            whoPays.addObject("you pay")
        }
        status.addObject(statusLabel.text!)
        arrayNumber++
        entityCellArray.append("\(names[arrayNumber)  -  \(amounts[arrayNumber])  -  \(dates[arrayNumber])  -  \(status[arrayNumber])")
        let created = UIAlertController(title: "success", message: "creation successful", preferredStyle: UIAlertControllerStyle.Alert)
        created.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
        presentViewController(created, animated: true, completion: nil)
        nameField.text = ""
        amountField.text = " "
        whoPaysLabel.text = "..."
        datePicker.date = newDate

        refreshTableView()
    }
    //test function, not to be implemented in app
    func printCount(){
       println(entityCellArray.count)

    }

    func refreshTableView(){
        self.tableView?.reloadData()
    }

    @IBAction func createButtonPressed(sender: UIButton){
        createNewEntity()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // Return the number of sections.
        return 1
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = entityCellArray[indexPath.row]
        return cell
    }
}

旁注:我是 swift 新手,我很肯定我的 tableView dataSourcedelegate 设置正确。希望有人能指出我做了什么来得到这个错误:[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

【问题讨论】:

  • 您的tableView 插座连接了吗?

标签: ios arrays swift uitableview reload


【解决方案1】:

如果tableView 插座未连接,您的reloadData 将无能为力。如果tableViewnil,则可选链self.tableView?.reloadData() 将不起作用,因为您忘记连接插座。

此错误[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' 表示您在数组中有一项,但您正试图访问索引1 处的项(这是第二项)。我怀疑你在这一行遇到了这个错误:

entityCellArray.append("\(names[arrayNumber)  -  \(amounts[arrayNumber])  -  \(dates[arrayNumber])  -  \(status[arrayNumber])")

您的一个数组怎么会相对于其他数组缺少一个元素?看这一行:

if let amountField_ = amountField.text.toInt() {
    amounts.addObject(amountField_)
}

如果amountField.text 未转换为整数,则amounts 的元素将少于其他数组,并且您的索引将超出amounts 的范围。请注意,即使是前导或尾随空格字符也会导致toInt() 失败。您可以将上述内容替换为:

// Use 0 if the field doesn't convert to Int
let amountField_ = amountField.text.toInt() ?? 0
amounts.addObject(amountField_)

【讨论】:

  • 谢谢。我无法将您的答案标记为正确,因为它只解决了一个问题:数组问题。请注意,我将 tableView 连接为插座(%100 肯定),但视图仍然没有显示数组。如果我执行这行代码:self.tableView.reloadData(),然后我得到这个错误:致命错误:在展开可选值时意外发现 nil
  • 另外,let amountField_ = amountField.text.toInt() 有问题?? 0. 我输入的第一个值是我在文本字段中输入的数字,但第二个值及以后的值都为零。对此我能做些什么吗? @vacawama
  • 当您清除 amountField 时,您将其设置为 " "(一个空格)。相反,您应该使用""(空字符串)。这就是导致您的 toInt() 第二次失败的原因。
  • 如果你的tableViewoutlet连接了,self.tableView.reloadData()不会得到致命错误,意外发现nil错误因为tableView不会为nil。
  • 谢谢你,你是我的英雄! @vacawama
【解决方案2】:

根据您的代码,此错误“[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'”应该来自 `cell.textLabel?.text = entityCellArray[indexPath.row]。只需检查 cellForRowAtIndexPath 中的 entityCellArray 计数是否为 0。

【讨论】:

    【解决方案3】:

    一般来说,您的代码看起来不错,您需要提供崩溃的位置以及不工作的地方。

    [__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' 告诉你你的数组之一是空的。在它崩溃的地方添加一个断点。

    对于 reloadData() 问题,有成千上万的原因导致无法正常工作。但是你必须自己弄清楚。在处添加断点 numberOfRowsInSectioncellForRowAtIndexPath 在调用 reloadData() 之后,看看它是否正确中断,并且您的数组具有您想要的内容。如果断点不起作用,则您的数据源不正确,或者您的 tableView 有 nil。重点是,你应该学会调试代码,而断点是你真正可以使用的工具。

    例如:

    添加断点后,尝试打印 self.tableView?.dataSource。如果您看到 dataSource 设置正确,那么我们可以确认必须调用 numberOfRowsInSectioncellForRowAtIndexPath,现在您可以在 numberOfRowsInSectioncellForRowAtIndexPath 处添加断点以查看损坏的内容。

    顺便说一句,我刚刚看到: @IBOutlet weak var tableView: UITableView! 这是一个弱属性,您可能需要在加载视图控制器后检查 self.tableView 是否存在。通常我们不会对 UIView 使用weak,除非您知道自己在做什么……您可以删除“weak”并比较结​​果。

    不要滥用weak来提高内存效率,因为它有其局限性,除非你知道自己在做什么。

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2015-12-06
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 2018-12-22
      • 2016-04-19
      相关资源
      最近更新 更多