首页 > 解决方案 > 核心数据获取结果不转换 NsManaged 子类

问题描述

    class DeviceModel: NSManagedObject {

            @NSManaged var deviceName: String?;
            @NSManaged var devicePrice: String?;

    }

class DeviceListController: UIViewController {

    var deviceList: [Any] = [];

    override func viewDidLoad() {
        super.viewDidLoad();


    }


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

        let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate;
        let context = appDelegate.persistentContainer.viewContext;
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Device");

        do {
            self.deviceList =  try context.fetch(request);
        } catch  {
            print(error);
        }
    }
}


extension DeviceListController: UITableViewDataSource, UITableViewDelegate {

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: DeviceItemCell.reuiseIdentifier) as? DeviceItemCell  else {
            fatalError("Error create tableCell")
        }

        guard let item = deviceList[indexPath.row] as? DeviceModel else {
            fatalError("Item not convertable DeviceModel");
        }

        cell.deviceName.text = item.value(forKey: "devicePrice") as! String

        return cell;

    }
}

让 item = deviceList[indexPath.row] 作为?NSManagedObject 可以工作,但是当我将 NSManagedObject 更改为我的 DeviceModel 类防护返回错误时,为什么我不将项目转换为 DeviceModel 类?但是 DeviceModel 类是子类 NsManagedObject

标签: swiftcore-dataswift4

解决方案


推荐阅读