所以从CoreData填充tableviewcell时遇到问题。在将实际数据填充到单元格之前,它会添加额外的白色单元格。
- 空白
- 空白
- 空白
- firstname1 lastname1
- firstname2 lastname2
- firstname3 lastname3
上面是表格视图的示例。
该应用程序首先从JSON下载数据,然后将该信息放入CoreData,然后从CoreData
(而非JSON)填充表格视图。
以下是代码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!
}
如果在将JSON保存到CoreData后删除self.tableView.reloadData()
,白细胞就会消失。但是,当我在应用程序中滚动时,屏幕外放置的单元格将被删除。这是我做IOS应用程序的第一次尝试,我正在尝试复制一些Android应用程序。顺便说一句,多余的白色单元格不是来自CoreData的“数据”,当从CoreData打印所有行时,它在日志中看起来是正确的。
答案 0 :(得分:0)
尝试使用自定义数据源而不是[NSManagedObject]。它可能会对您有所帮助。
答案 1 :(得分:0)
问题是我使用了错误的合并策略。
我有:
context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.overwrightMergePolicyType)
更改为:
context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
删除空单元格=)