核心数据:无法将类型“MyType_MyType_2”的值转换为MyType [英] Core Data: Could not cast value of type 'MyType_MyType_2' to MyType

查看:151
本文介绍了核心数据:无法将类型“MyType_MyType_2”的值转换为MyType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Objective-C模型类MyType。这个类用于Swift代码:

  NSEntityDescription.insertNewObjectForEntityForName(MyType,inManagedObjectContext:context )as! MyType 

错误消息

 核心数据:无法将MyType_MyType_2类型的值(0x7be99a30)转换为MyType(0xf33db74)。 

如果我把它转换为 NSManagedObject 。当我打印结果,我仍然可以看到,它是MyType的实际实例:

 < MyType:0x7ae06d50& (entity:MyType; id:0x7aeba6d0< x-coredata:/// MyType / t957F2860-85F8-46E0-B6D6-4D1DF6C4EC613>; data:{
... fields ...
} )

这里发生了什么? MyType_MyType_2 来自哪里?

解决方案

这个问题,是因为我忘了在实体上设置类。这是我想出的:


  1. 点击文件结构/项目中的.xcdatamodelId文件
    导航窗格)。

  2. 选择您遇到问题的实体。

  3. 在实用程序窗格(最右侧)中,查找看起来像1997年手机(数据模型检查器)的图标。

  4. 在实体设置下,您应该会看到两个字段Name和Class - 使用您正在使用的类的名称设置Class名称)。

您甚至会注意到,在按照这些步骤之前,默认的类是NSObject, 。我发现了一些程序化的方法来做到这一点,但这似乎是最简单/最快的解决方案。



我应该注意,我的模型WAS写在Swift,添加由@zellb提到的@objc(Entity)互操作性引用。但是,只要你正确地做这个部分(这将导致与我的理解不同的不相关的错误),这不应该在解决方案中产生影响。


I have an Objective-C model class MyType. This class is used in Swift code:

NSEntityDescription.insertNewObjectForEntityForName("MyType", inManagedObjectContext: context) as! MyType

The 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. When I print the result, I can nevertheless see, that it is an actual instance of 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?

解决方案

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:

  1. Click on .xcdatamodelId file in your file structure/project navigator pane (far left).
  2. Select the entity that you are having issues with.
  3. In the Utilities pane (far right), look for the icon that looks like a 1997 cell phone, the Data Model Inspector.
  4. Under the entity settings, you should see two fields, "Name" and "Class" - set up "Class" with the name of the class you are using (typically the same as "Name").

You'll even notice before you follow these steps that the default "class" is NSObject, reflecting the error message. 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. 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).

这篇关于核心数据:无法将类型“MyType_MyType_2”的值转换为MyType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆