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