首页 > 解决方案 > 从 CoreData 填充的自定义 tableView,提供额外的白色单元格

问题描述

所以从CoreData填充我的tableviewcells时我遇到了问题。在将我的真实数据填充到单元格之前,它会添加额外的白色单元格。

  • 空白的
  • 空白的
  • 空白的
  • 名 1 姓 1
  • 名 2 姓 2
  • 名 3 姓 3

上面是 tableview 的外观示例。

该应用程序首先从 JSON 下载数据,然后将该信息放入 CoreData,然后CoreData从而不是 JSON 填充 tableview。下面是代码viewController.swift

import UIKit
import CoreData

class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!

var people: [NSManagedObject] = []
var involvedJSON = [InvolvedJSON]()

final let JSONUrl = URL(string: "http://JSON_URL")

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

        downloadJson()

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }

    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "InvolvedOnline")

    do {
        people = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

func downloadJson(){
    guard let downloadURL = JSONUrl else {return}

    URLSession.shared.dataTask(with: downloadURL) { (data, urlResponse, error) in

        guard let data = data, error == nil, urlResponse != nil else {
            print ("Something is wrong")
            return
        }
        do
        {
            let decoder = JSONDecoder()
            let downloadedInvolved = try decoder.decode([InvolvedJSON].self, from: data)
            self.involvedJSON = downloadedInvolved
            for i in 0 ..< downloadedInvolved.count{
                let wristband_uid = downloadedInvolved[i].wristband_uid
                let security_id = downloadedInvolved[i].security_id
                let firstname = downloadedInvolved[i].firstname
                let lastname = downloadedInvolved[i].lastname
                let gender = downloadedInvolved[i].gender
                let priority = downloadedInvolved[i].priority
                let status = downloadedInvolved[i].status
                let creator_id = downloadedInvolved[i].creator_id
                let created_millis = downloadedInvolved[i].created_millis
                let priority_millis = downloadedInvolved[i].priority_millis
                let created_time = downloadedInvolved[i].created_time
                let priority_time = downloadedInvolved[i].priority_time

                // SAVE DATA to DATACORE InvolvedOnline
            DispatchQueue.main.async {
                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                let context = appDelegate.persistentContainer.viewContext
                context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.overwriteMergePolicyType)
                let entity = NSEntityDescription.entity(forEntityName: "InvolvedOnline", in: context)
                let item = NSManagedObject(entity: entity!, insertInto: context)

                item.setValue(wristband_uid, forKey: "wristband_uid")
                item.setValue(security_id, forKey: "security_id")
                item.setValue(firstname, forKey: "firstname")
                item.setValue(lastname, forKey: "lastname")
                item.setValue(gender, forKey: "gender")
                item.setValue(priority, forKey: "priority")
                item.setValue(status, forKey: "status")
                item.setValue(creator_id, forKey: "creator_id")
                item.setValue(created_millis, forKey: "created_millis")
                item.setValue(priority_millis, forKey: "priority_millis")
                item.setValue(created_time, forKey: "created_time")
                item.setValue(priority_time, forKey: "priority_time")
                do {
                    try context.save()
                    //print("saving success")
                    self.people.append(item)
                    self.tableView.reloadData()
                } catch {
                    print("Failed saving")
                }

            }

        }
        } catch {

        }
        }.resume()

}




}
extension ViewController: UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return people.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let per = people[indexPath.row]

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "InvolvedCell", for: indexPath) as? InvolvedCell else { return UITableViewCell()}

    cell.nameLbl.text = per.value(forKeyPath: "firstname") as? String
    cell.secidLbl.text = per.value(forKeyPath: "security_id") as? String
    cell.priorityLbl.text = per.value(forKeyPath: "priority") as? String
    cell.priorityTimeLbl.text = per.value(forKeyPath: "priority_time") as? String

    return cell
    }
}

下面是我的 InvolvedCell.swift

import UIKit

class InvolvedCell: UITableViewCell {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var secidLbl: UILabel!
@IBOutlet weak var priorityLbl: UILabel!
@IBOutlet weak var priorityTimeLbl: UILabel!

}

如果我self.tableView.reloadData()在 JSON 保存到 CoreData 后删除,白色单元格就会消失。但是当我在应用程序中滚动时,屏幕外的单元格会被删除。这是我第一次尝试做一个 IOS 应用程序,我试图复制我的一些 android 应用程序。顺便说一句,额外的白色单元格不是来自 CoreData 的“数据”,当从 CoreData 打印所有行时,它在日志中看起来是正确的。

标签: iosswiftxcodeuitableview

解决方案


尝试使用您的自定义数据源而不是 [NSManagedObject]。它可能会对您有所帮助。


推荐阅读