表视图中空数组的Swift索引0超出范围

Posted

技术标签:

【中文标题】表视图中空数组的Swift索引0超出范围【英文标题】:Swift index 0 beyond bounds for empty array in tableview 【发布时间】:2015-03-22 22:07:13 【问题描述】:

我正在尝试使用 PFTableViewCell 连接到主电视控制器的 2 个标签来填充 tableview

当我添加 (numberOfSectionsInTableView + numberOfRowsInSection ) 应用程序崩溃

但是当我删除它时它可以工作,但它什么也没显示。

这是表格视图单元格

class courseCell: PFTableViewCell 

    @IBOutlet var name: UILabel!

    @IBOutlet var location: UILabel!


这是表格视图控制器

class courseTVC: PFQueryTableViewController 


override init!(style: UITableViewStyle, className: String!) 
    super.init(style: style, className: className)



required init(coder aDecoder:NSCoder)

    super.init(coder:aDecoder)



    self.parseClassName = "courses"
    self.textKey = "Location"
    self.pullToRefreshEnabled = true
    self.paginationEnabled = false


override func queryForTable() -> PFQuery! 
    var query = PFQuery(className: "courses")
    query.orderByDescending("Location")
    return query



  override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
        return 1
    

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return 4



override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell 
    var cell = tableView.dequeueReusableCellWithIdentifier("cell" , forIndexPath : indexPath) as? courseCell
    if cell == nil
    
        cell = courseCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    


    cell!.name.text = object["Price"] as! String!
    cell!.location.text = object["Location"] as! String!




    return cell!

我不知道如何解决这个问题

【问题讨论】:

【参考方案1】:

查看PFQueryTableViewController、https://www.parse.com/docs/ios/api/Classes/PFQueryTableViewController.html 的文档,您似乎不应该覆盖这两种方法。

应该已经根据objects 为表中的所有行调用– tableView:cellForRowAtIndexPath:object:。您不应该覆盖 numberOfSectionsInTableViewnumberOfRowsInSection,因为 Parse 控制器会为您处理所有这些。您正在重写这些方法并硬编码一个数字,这会导致 Parse 尝试获取和对象超出范围(它不存在)的行。看起来您的数据源中实际上没有对象。

【讨论】:

是的,我第一次跳过了这两种方法“delete”,但视图控制器什么都没有,如果你能看到 Parse 的对象的两个图像 + 空表视图从 parse 的数据源“核心”中获取任何内容" 有两个标签连接到PFTableViewCell 知道问题是你的答案+类应该是大写的:) @JamesMoriarty 你能发布你修复的屏幕截图吗?我在使用 PFTableView 时遇到了这个问题,现在我又在使用 PFCollectionViewController 时遇到了这个问题。不记得我是如何修复它的。

以上是关于表视图中空数组的Swift索引0超出范围的主要内容,如果未能解决你的问题,请参考以下文章

当我使用单元格时索引超出范围(Swift)

致命错误:在Swift中访问10个元素的数组时,数组索引超出范围

UICollectionView 数组索引超出范围

Swift 致命错误:数组索引超出范围

Swift 致命错误:数组索引超出范围

尽管表大于索引,但表索引超出范围