CoreData信息未显示在表格单元格中

时间:2017-07-29 12:09:34

标签: ios swift xcode core-data ios10

我有自定义单元格并使用核心数据,单元格未更新。 起初我使用Manual / None Codegen选项在。 xcdatamodeId 创建了一些实体。该项目不会构建,并会给我这个错误:

/ # docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ab192edf5872 luisbebop/echo-server "/opt/echo-server/..." 2 minutes ago Up About a minute 0.0.0.0:8800->8800/tcp echo-server / # netstat -nltup Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name

在我为我的模型生成的类文件并删除了所有 @objc(Item)行之后,项目已经构建,但模拟器的单元格中没有任何内容。自定义单元格有一个标识符,用于 cellForRowAt 函数的代码中,我也生成测试数据,我可以像这样访问 AppDelegate

'An NSManagedObject of class 'DreamLister.Item' must have a valid NSEntityDescription.'

编辑:在建议将codegen选项更改为类定义后,构建失败并出现Swift编译错误: 命令:let ad = UIApplication.shared.delegate as! AppDelegate let context = ad.persistentContainer.viewContext

这是我的控制器的代码

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

ItemCell的代码

import UIKit
import CoreData

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var segment: UISegmentedControl!

    var controller: NSFetchedResultsController<Item>!


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        generateTestData()
        attemptFetch()


    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell

        configureCell(cell: cell, indexPath: indexPath as NSIndexPath)

        return cell

    }

    func configureCell(cell: ItemCell, indexPath: NSIndexPath) {

        let item = controller.object(at: indexPath as IndexPath)
        cell.configureCell(item: item)

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let objs = controller.fetchedObjects , objs.count > 0 {

            let item = objs[indexPath.row]
            performSegue(withIdentifier: "ItemDetailsVC", sender: item)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ItemDetailsVC" {
            if let destination = segue.destination as? ItemDetailsVC {
                if let item = sender as? Item {
                    destination.itemToEdit = item
                }
            }
        }

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let sections = controller.sections {

            let sectionInfo = sections[section]
            return sectionInfo.numberOfObjects
        }

        return 0
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 150
    }

    func attemptFetch() {

        let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
        let dateSort = NSSortDescriptor(key: "created", ascending: false)

        fetchRequest.sortDescriptors = [dateSort]

        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

        controller.delegate = self

        self.controller = controller

        do {

            try controller.performFetch()

        } catch {

            let error = error as NSError
            print("\(error)")

        }

    }

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        switch(type) {

        case.insert:
            if let indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .fade)
            }
            break
        case.delete:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            break
        case.update:
            if let indexPath = indexPath {
                let cell = tableView.cellForRow(at: indexPath) as! ItemCell
                configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
            }
            break
        case.move:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            if let indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .fade)
            }
            break

        }
    }


    func generateTestData() {

        let item = Item(context: context)
        item.title = "MacBook Pro"
        item.price = 1800
        item.details = "I can't wait until the September event, I hope they release new MPBs"

        let item2 = Item(context: context)
        item2.title = "Bose Headphones"
        item2.price = 300
        item2.details = "But man, its so nice to be able to block out everyone with the noise canceling tech."

        let item3 = Item(context: context)
        item3.title = "Tesla Model S"
        item3.price = 110000
        item3.details = "Oh man this is a beautiful car. And one day, I willl own it"


        ad.saveContext()


    }


}

和核心数据生成文件的代码

物品+ CoreDataClass.swift

import UIKit

class ItemCell: UITableViewCell {

    @IBOutlet weak var thumb: UIImageView!
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var details: UILabel!

    func configureCell(item: Item) {

        self.title.text = item.title
        self.price.text = "$\(item.price)"
        self.details.text = item.details

    }

}

物品+ CoreDataProperties.swift

import Foundation
import CoreData


public class Item: NSManagedObject {

    public override func awakeFromInsert() {

        super.awakeFromInsert()

        self.created = NSDate()
    }

}

任何想法或想法? 在此先感谢。

2 个答案:

答案 0 :(得分:0)

在核心数据文件中选择“实体”和“选择Codegen”选项以进行类别定义并运行并查看

答案 1 :(得分:0)

我再次删除并创建了核心数据的生成文件,并且我还将MainVC上这两个函数的return语句从零返回到此。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = controller.sections {

      let sectionInfo = sections[section]
      return sectionInfo.numberOfObjects

    } else {

     return 0
    }


func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}