【发布时间】:2018-05-31 00:08:31
【问题描述】:
注意:问题虽然有CoreData的例子,但和CoreData无关,只是一个例子
我们正在开发一个使用 CoreData 作为缓存层的 Swift 项目。
我们在mainViewController 中经常使用Notifications 来收听我们的NSManagedObjectContext 有新变化后的变化。
在我们添加具有以下层次结构的新实体之前,这非常有效:
- 实体
Vehicle是具有一些属性的基类。 - 实体
Car是Vehicle的子类,具有特定属性和与Human实体的toMany 关系。 - 实体
Human是具有特定属性的基类,与Car有关系。
问题出在以下几点:
当添加新的Car 对象时,通知会触发,在mainViewController 中,我们需要检查它是否为Car 类型,如下所示:
if let insertedObjects = notification.userInfo?[NSInsertedObjectsKey] as? Set<Car> {
print("we have some cars") // this will never execute
}
向下转换的Set<Car> 类型永远不会计算为真,因为Set 具有Car 和Human 类型的元素。
我想要什么:
检查Set 是否具有Car 或Human 类型的NSManagedObject 子类,因为我对其进行了向下转换。
我想做什么:
将其向下转换为NSManagedObject,并通过添加以下where 条件来检查Set 是否包含Car:insertedObjects.contains(Car),但它有一个编译时错误:
Cannot convert value of type '(Car).Type' to expected argument type 'NSManagedObject'
如果您有任何问题,请告诉我,而不仅仅是投反对票。
【问题讨论】: