【问题标题】:Data won't load from core-data local storage数据不会从核心数据本地存储加载
【发布时间】:2019-05-25 20:47:44
【问题描述】:

我已将多个核心数据对象保存到我的核心数据存储中,并且我还打印了核心数据对象中的项目数量,它显示为 4。不幸的是,它从未达到 cellForRowAtIndexPath 方法来加载我没有的数据知道为什么。

这是我的视图控制器:

import UIKit
import CoreData

class CustomersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DataReceived {
    
    //MARK: - Variables
    @IBOutlet weak var customersTableView: UITableView!
    var customers = [Customer]()
    var customersModel = [CustomerModel]()
    var context = PersistanceService.context
    
    //MARK: - Lifecycle Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 0.4772838354, green: 0.7987893224, blue: 0.9529026151, alpha: 1)
        customersTableView.backgroundColor = #colorLiteral(red: 0.4772838354, green: 0.7987893224, blue: 0.9529026151, alpha: 1)
        if loadData() {
            print("loading items from local persistancy")
        } else {
            print("local persistancy is empty")
        }
        customersTableView.dataSource = self
        customersTableView.delegate = self
        customersTableView.register(UINib(nibName: "CustomerCell", bundle: nil), forCellReuseIdentifier: "customer")
        
    }
    
    //MARK: - Tableview delegate & datasource methods
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customer", for: indexPath) as! CustomerCell
        let currentCustomer = customersModel[indexPath.row]
        cell.nameAndRegionLabel.text = "\(currentCustomer.name!) from \(currentCustomer.region!)."
        cell.genderAndAgeLabel.text = "\(currentCustomer.gender!), \(currentCustomer.age) Years Old."
        cell.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 20
        cell.clipsToBounds = true
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let item = customersModel.remove(at: indexPath.row)
            context.delete(item)
            tableView.deleteRows(at: [indexPath], with: .fade)
            saveData()
            
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customers.count
    }
    
    //MARK: - Segue methods
    
    @IBAction func moveToNewCostumerVC(_ sender: Any) {
        performSegue(withIdentifier: "newCustomer", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "newCustomer" {
            let newCustomerVC = segue.destination as! NewCustomerViewController
            newCustomerVC.delegate = self
        }
    }
    
    // MARK: - New Customer Data Delegate Method & Saving to Core Data
    func dataReceived(customer: CustomerModel) {
        customersModel.append(customer)
        customersTableView.reloadData()
        print(customersModel.count)
        saveData()
        customersTableView.reloadData()
    }
    
    func saveData(){
        do {
            try context.save()
            print("data saved successfully")
        } catch {
            print("error saving context, \(error.localizedDescription)")
        }
    }
    
    //MARK: - Retrieving From Core Data
    func loadData()->Bool{
        
        let fetchRequest : NSFetchRequest<CustomerModel> = CustomerModel.fetchRequest()
        do {
            var customersFromPersistancy = try PersistanceService.context.fetch(fetchRequest)
            print(customersFromPersistancy.count)
            if customersFromPersistancy.count == 0 {return false}
            customersFromPersistancy = customersModel
            return true
        } catch {
            print("error fetching from core data, \(error)")
            return false
        }
    }
}

如您所见,在 loadData() 函数中,我打印核心数据对象数组中的对象数量,运行应用程序时的结果为 4。之后我调用 tableView.reloadData() 方法应该(?)调用 cellForRowAtIndexPath 并从头开始重新加载数据集,但它永远不会这样做。 谢谢!

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    在加载时你改变这个变量

    if customersFromPersistancy.count == 0 {return false}
       customersFromPersistancy = customersModel <<< here
    

    numberOfRowsInSection 中返回空数组

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

    这会导致 tableView 为空,因此请确保更改 tableView 的 dataSource 数组的内容

    你使用

    let currentCustomer = customersModel[indexPath.row] 
    

    cellForRowAt 内部,将多个数组作为 dataSource 并不是最佳做法,因此请确保它只有 1 个


    编辑:

        let fetchRequest : NSFetchRequest<CustomerModel> = CustomerModel.fetchRequest()
        do {
            var customersFromPersistancy = try PersistanceService.context.fetch(fetchRequest)
            print(customersFromPersistancy.count)
            customersModel = customersFromPersistancy 
            if customersFromPersistancy.count == 0 {return false} 
            return true
        } catch {
            print("error fetching from core data, \(error)")
            return false
        }
    

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

    【讨论】:

    • 所以如果我理解正确,我应该在更改变量后调用 reloadData() 来解决问题?
    • 刚刚试过 ^ 并没有用,所以我在等你澄清你的真正意思
    • 不明白你在编辑数组之后究竟是什么意思,你的意思是我持有多个对象数组?
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2015-06-18
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多