数据不会从核心数据本地存储中加载

时间:2019-05-25 20:47:44

标签: swift uitableview core-data

我已将多个核心数据对象保存到我的核心数据存储中,并且还打印了核心数据对象中的项目数量,它显示为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: - Retreving 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并从头开始重新加载数据集,但绝不会这样做。 谢谢!

1 个答案:

答案 0 :(得分: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
}