【问题标题】:Core Data: no index path for table cell being reused, Cells disappearing核心数据:没有重复使用表格单元格的索引路径,单元格消失
【发布时间】:2016-06-08 09:00:25
【问题描述】:

我正在尝试制作一个应用程序,它可以在 Core Data 中保存一些条目,并且还可以选择在线同步它。我想要的是,当文档同步时,它在单元格的 imageView 和背景上有不同的图像,我发送请求以获取所有同步文档的唯一 ID。因此,每当文档同步时,它的 imageView 的图像就会发生变化。所以,到目前为止,我已经做到了。

override func viewDidLoad() {
    super.viewDidLoad()
    self.syncedIds = NSMutableArray()
}
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tokenAndIds = NSMutableArray()


    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let authToken = prefs.valueForKey("authToken") as! String

    values["auth_code"] = "\(authToken)"

    self.checkSync()

    NSTimer.scheduledTimerWithTimeInterval(6.0, target: self, selector: #selector(ReceiptsListViewController.checkSync), userInfo: nil, repeats: true)

}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier as String, forIndexPath: indexPath) as! ReceiptsViewCell

    // Configure the cell...

    let entry: DiaryEntry = self.fetchedResultsController.objectAtIndexPath(indexPath) as! DiaryEntry

    cell.configureCellForEntry(entry)
    cell.imageButton.tag = indexPath.row

    if (self.tableView.editing) {
        cell.imageButton.hidden = true
    } else {
        cell.imageButton.hidden = false
    }

    if (cell.syncImageView.image == UIImage(named: "syncing")) {

        let idString: String = "\(cell.idParam!)"
        tokenAndIds.addObject(idString)
    }



    if (syncedIds != nil) {
        for i in 0 ..< syncedIds.count {
            if (syncedIds[i] as! String == "\(cell.idParam!)") {

                print("Synced Ids are: \(syncedIds[i])")

                let cell1 = tableView.dequeueReusableCellWithIdentifier(CellIdentifier as String, forIndexPath: indexPath) as! ReceiptsViewCell

                let entry: DiaryEntry = self.fetchedResultsController.objectAtIndexPath(indexPath) as! DiaryEntry
                entry.sync = 2

                let coreDataStack: CoreDataStack = CoreDataStack.defaultStack
                coreDataStack.saveContext()

                cell1.configureCellForEntry(entry)

                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
                                  cell.syncImageView.image = UIImage(named: "sync")

            }
        }
    }

    return cell
}

func checkSync() {

    if (tokenAndIds != nil && tokenAndIds != []) {
        let idArray: NSMutableArray = tokenAndIds


        let myUrl = NSURL(string: "http://10.0.0.4:81/iphone/sync.php")

        let request = NSMutableURLRequest(URL: myUrl!)
        request.HTTPMethod = "POST"

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        values["idArray"] = idArray

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            (let data, let response, let error) in

            if let _ = response as? NSHTTPURLResponse {
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                    if error != nil {
                        print("error=\(error!)")
                        return
                    }
                    if let parseJSON = json {


                        for (key, value) in parseJSON {

                            if (value as! String == "0") {
                                print(key)

                                self.syncedIds.addObject(key)
                            }
                        }

                    }
                } catch {
                    print("Error is Here: \(error)")
                }
            }
        }
        task.resume()
    }

}

但问题是,当我收到有关所有同步 ID 的响应,然后我进入另一个视图,然后返回对 syncImageView 进行更改时,单元格继续消失,我也收到此警告:“不被重复使用的单元格的索引路径。”我知道这与 cellForRowAtIndexPath 方法有关,但它是什么?另外,如果我停止应用程序并重新运行它,那么一切都会像 imageView 一样被修复并且没有单元格消失。

【问题讨论】:

  • 不要在cellForRowAtIndexPath(视图)中使用重复循环进行大量计算。根据模型-视图-控制器模式在控制器中进行计算,然后将结果放入数据源数组(模型),然后调用reloadData()刷新UI(视图)。
  • 看起来syncedIds 应该是一个字典,而不是一个数组,但是你的大问题是从 inside cellForRowAtIndexPath 调用reloadRowsAtIndexPaths 并且没有必要调用dequeueReusableCellWithIdentifier 两次 - 只需获取单元格并根据需要进行配置
  • @Paulw11 我试过在没有 reloadRows 和 dequeReusable 的情况下这样做,但它变得更糟。
  • 这很难想象。您当然不需要cell1 - 您可以使用cell,如果您将同步的 Id 存储在一个集合中,您可以摆脱 for 循环并在此函数中重新加载单元格是错误消息的原因
  • 好的,第一点我明白了,但是第二点,你能详细说明一下吗?

标签: ios swift uitableview core-data nsindexpath


【解决方案1】:

问题是cellForRowAtIndexPath 中的异步调用。您需要获取您的代码(在 tableView 数据源和委托之外),一旦您获取了数据(并且可能存储在某种类型的集合中,如数组),请在您的 tableView 上调用 reloadData() 并刷新数据。

cellForRowAtIndexPath 应该寻找现有数据,而不是获取数据。 indexPath.row 用于调用您的收藏索引并获取相应的数据。

当您的异步调用完成时,cellForRowAtIndexPath 已经完成,并且对您尝试更新的单元格的引用不再存在(因此出现错误)。

提示:

请记住,在后台线程中获取数据后,请务必在主线程上调用 reloadData()

【讨论】:

  • 谢谢,我也是这么想的。我正在考虑单独解析整个表格视图。那会是个好主意吗。我会在 1-2 天内检查代码。
猜你喜欢
  • 2013-08-31
  • 2017-08-05
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多