找到你要的答案

Q:insertDataforTableName returns wrong object type

Q:insertdatafortablename返回错误的对象类型

I'm building out some new functionality in my app which is essentially just old code copied for a new class type. Before it was creating and displaying vehicles, and now it's creating and displaying books, however it's not behaving as expected.

I want to persist the data, so here is the code which creates a new ManagedObject, which should return a pointer to the object:

vehicle = [[MyCoreDataManager sharedManager] insertDataforTableName:@"MyVehicle"];

This line returns an object of type MyVehicle, which is what I want. MyVehicle is a class which inherits from NSManagedObject and has its own methods which are immediately used after inserting.

Now I want to have the same exact arrangement, except with a MyBook object. However, when I run:

book = [[MyCoreDataManager sharedManager] insertDataforTableName:@"MyBook"];

The above line of code returns an object of type NSManagedObject, which is wrong because I can't access the MyBook methods because it's an NSManagedObject and not a MyBook. I even tried type casting, but it doesn't work. The fact that it is an NSManagedObject and not a MyBook is causing my app to crash with an unrecognized selector sent to instance exception because I am trying to call a method which is not recognized by the object at runtime. Your thoughts are appreciated.

My understanding of the problem is that somehow the MyBook class is not properly declared or has some subtle issue in its .h or .m file which is causing it not to link up at runtime. Or some kind of problem with the .xcdatamodeld entity definition.

我在我的应用程序中建立了一些新的功能,这基本上只是一个新的类类型复制的旧代码。之前,它是创造和显示车辆,现在它的创建和显示书籍,但它的表现不如预期。

我想坚持的数据,所以这里是创建一个新的管理对象的代码,它将返回一个对象的指针:

vehicle = [[MyCoreDataManager sharedManager] insertDataforTableName:@"MyVehicle"];

这条线返回对象的类型我的车子,这就是我想要的。我的车子是一个类,继承自NSManagedObject,有自己的方法,插入后立即使用。

现在我想有相同的配置,除了自动的对象。然而,当我奔跑:

book = [[MyCoreDataManager sharedManager] insertDataforTableName:@"MyBook"];

上面这行代码返回类型NSManagedObject对象,这是错误的因为我不能进入我的书的方法,因为它是NSManagedObject,不是我的书。我什至尝试型铸造,但它不工作。事实上,这是一个而不是一个自动的NSManagedObject引起我的应用程序崩溃无法识别的选择因为我想打电话给一个不认识的对象在运行时发出异常的方法实例。感谢你的想法。

我对这个问题的理解是,不知怎的,我的书类不正确声明或有一些微妙的问题的。H或M文件导致它没有连接起来,在运行时。或某一类问题的xcdatamodeld实体的定义。

answer1: 回答1:

Rob Mayoff was correct to ask:

Does the definition of the "MyBook" entity in the data model specify "MyBook" as its class?

Because in this case it did not. If you ever want to create a new entity in your data model, be sure to specify the actual class that it is associated with in the right hand toolbar. It's pretty easy to miss this step, if you ask me.

Rob Mayoff是正确的问:

没有“我”的实体的定义在数据模型中指定“自动”为课吗?

因为在这种情况下,它没有。如果您想在数据模型中创建一个新实体,请务必指定它与右工具栏关联的实际类。这很容易错过这一步,如果你问我。

objective-c  core-data