没有索引路径表格单元格在Swift中重用

Ale*_*ser 6 uitableview tableview ios swift

我注意到在Obj-C中有很多问题,但我几乎不记得Obj-C,每个答案都是针对这个问题的.在这里我得到这个错误:"有时当应用程序刷新时,表单元格没有重复使用的索引路径".我注意到,当我不刷新但是我离开并重新打开表视图时,格式化已经毁了.

这是我在几个地方使用的"刷新"方法:

   @IBAction func loadData(){
        timeLineData.removeAllObjects()
        //pulls the data from the server
        var findTimeLineData: PFQuery = PFQuery(className: "Sweets")
        findTimeLineData.findObjectsInBackgroundWithBlock{
            (objects:[AnyObject]!, error: NSError!) -> Void in
            if !error{
                for object:PFObject! in objects{
                    self.timeLineData.addObject(object)
                }
                let tempArray: NSArray = self.timeLineData.reverseObjectEnumerator().allObjects
                self.timeLineData = tempArray as NSMutableArray

                //reloads the data in the table view
                self.tableView.reloadData()
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

而tableview方法:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
    let cell: SweetTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SweetTableViewCell

    let sweet: PFObject = self.timeLineData.objectAtIndex(indexPath.row) as PFObject

    //part of the animation
    cell.sweetTextView.alpha = 0
    cell.userNameLabel.alpha = 0
    cell.timestampLabel.alpha = 0


    cell.sweetTextView.text = sweet.objectForKey("content") as String

    //add the date
    var dateFormatter: NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "HH:mm yyyy-MM-dd"
    cell.timestampLabel.text = dateFormatter.stringFromDate(sweet.createdAt)

    //finds the sweeter associated with a pointer
    var findSweeter: PFQuery = PFUser.query()
    findSweeter.whereKey("objectId", equalTo: sweet.objectForKey("sweeter").objectId)

    findSweeter.findObjectsInBackgroundWithBlock{
        (objects: [AnyObject]!, error: NSError!)-> Void in
        if !error{
            let user: PFUser = (objects as NSArray).lastObject as PFUser
            cell.userNameLabel.text = user.username
        }

    }

    //adds animation
    UIView.animateWithDuration(1, animations: {
        cell.sweetTextView.alpha = 1
        cell.userNameLabel.alpha = 1
        cell.timestampLabel.alpha = 1
    })

    return cell
}
Run Code Online (Sandbox Code Playgroud)

知道造成错误的原因是什么吗?

小智 0

是什么导致了您的问题:当您滚动表格时,TableView 会使您对解析服务器的异步调用尝试操作的单元格出列。

您可以通过以下方式解决此问题: 1- 在 Parse 上的 Sweets 表中,将 PFUser 对象存储为指针 2- 在 loadData 函数中,通过 PFQuery 的 includeKey 方法从查询中获取用户

如果您根据此进行更改,则不必在每次调用 cellForRowAtIndexPath 时都查询 PFUser。