核心数据:没有重复使用表格单元格的索引路径,单元格消失

时间:2016-06-08 09:00:25

标签: ios swift uitableview core-data nsindexpath

我正在尝试创建一个可以在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的响应然后我进入另一个View然后回来对syncImageView进行更改时,单元格继续消失,我也收到此警告:“no正在重用的单元的索引路径。“我知道这与cellForRowAtIndexPath方法有关,但它是什么?此外,如果我停止应用程序并重新运行它,那么一切都会被修复,就像imageView被更改一样,没有单元格消失。

1 个答案:

答案 0 :(得分:0)

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

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

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

提示

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