swift - 核心数据获取结果不转换 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
解决方案
推荐阅读
- html - 如何在移动设备中添加字体真棒选择选项?
- angular - 如果标签标题在第二个组件(Angular)中,则不显示标签标题
- javascript - 如何使用 \n
或类似方法在 React 中的变量内格式化文本 - javascript - 当我显示面板时,YUI (YAHOO) 阻止了我的 UI
- excel - 比较两个不同工作表中的两列
- android - 添加线性布局会弄乱预览中的布局(Android Studio)
- python - 使用熊猫图在 groupby 之后进行子图
- python-3.x - 我无法访问我的 Kivy 代码的“根”
- database - 在 CosmosDb 查询中获取 TotalResults
- azure-cognitive-services - 在使用 azure 表单识别器进行医疗处方时,一些键值对(如数量和笔芯数)没有被提取