[英]Core Data: Could not cast value of type 'MyType_MyType_2' to MyType
I have an Objective-C model class MyType.我有一个 Objective-C 模型类 MyType。 This class is used in Swift code:
这个类在 Swift 代码中使用:
NSEntityDescription.insertNewObjectForEntityForName("MyType", inManagedObjectContext: context) as! MyType
The as!
as!
cast results in the error message强制转换导致错误消息
Core Data: Could not cast value of type 'MyType_MyType_2' (0x7be99a30) to MyType (0xf33db74).
If I cast it as NSManagedObject
it works.如果我将其转换为
NSManagedObject
它就可以工作。 When I print the result, I can nevertheless see, that it is an actual instance of MyType:当我打印结果时,我仍然可以看到,它是 MyType 的一个实际实例:
<MyType: 0x7ae06d50> (entity: MyType; id: 0x7aeba6d0 <x-coredata:///MyType/t957F2860-85F8-46E0-B6D6-4D1DF6C4EC613> ; data: {
...the fields...
})
What is happening here?这里发生了什么? And where does the name
MyType_MyType_2
come from? MyType_MyType_2
这个名字MyType_MyType_2
而来?
When I had this issue, it was because I had forgotten to set the "class" on the entity.当我遇到这个问题时,是因为我忘记在实体上设置“类”。 This is what I came up with:
这就是我想出的:
You'll even notice before you follow these steps that the default "class" is NSObject, reflecting the error message.在执行这些步骤之前,您甚至会注意到默认的“类”是 NSObject,反映了错误消息。 I found some programatic ways to do this too, but this seemed like the simplest/quickest solution.
我也找到了一些编程方法来做到这一点,但这似乎是最简单/最快的解决方案。
I should note that my model WAS written in Swift, so I did have to add the @objc(Entity) interoperability reference mentioned by @zellb.我应该注意到我的模型是用 Swift 编写的,所以我必须添加 @zellb 提到的 @objc(Entity) 互操作性参考。 But that shouldn't make a difference in the solution as long as you are doing that part properly (and that would cause a different unrelated error from my understanding).
但是,只要您正确地完成了那部分工作,这就不会对解决方案产生影响(这会导致与我的理解不同的不相关错误)。
just try this:试试这个:
@objc(MyType)
public class MyType: NSManagedObject {
// your class
}
instead of this:而不是这个:
class MyType: NSManagedObject {
// your class
}
I had mistakenly set a "parent entity" in one of my entities in the data model inspector in the entity section.我错误地在实体部分的数据模型检查器中的一个实体中设置了“父实体”。 I mistakenly thought that referred to the destination of a one-to-many relationship.
我错误地认为,指的是一对多关系的目的地。
Setting it back to "no parent entity" fixed the problem, although I did have to delete and reinstall the app in the simulator to deal with the messed up core data database.将其设置回“无父实体”解决了问题,尽管我确实必须在模拟器中删除并重新安装应用程序以处理混乱的核心数据数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.