简体   繁体   English

我可以向Core Data生成的类添加自定义方法吗?

[英]Can I add a custom method to Core Data-generated classes?

I've got a couple of Core Data-generated class files that I'd like to add custom methods to. 我有几个Core Data生成的类文件,我想向它们添加自定义方法。 I don't need to add any instance variables. 我不需要添加任何实例变量。 How can I do this? 我怎样才能做到这一点?

I tried adding a category of methods: 我尝试添加一种方法:

// ContactMethods.h (my category on Core Data-generated "Contact" class)
#import "Contact.h"
@interface Contact (ContactMethods)
-(NSString*)displayName;
@end
...
// ContactMethods.m
#import "ContactMethods.h"
@implementation Contact (ContactMethods)
-(NSString*)displayName {
    return @"Some Name"; // this is test code
    }
@end

This doesn't work, though. 但是,这不起作用。 I get a compiler message that "-NSManagedObject may not respond to 'displayName' " and sure enough, when I run the app, I don't get "Some Name" where I should be seeing it. 我收到一个编译器消息,即“ -NSManagedObject可能不响应'displayName'”,并且可以肯定的是,当我运行该应用程序时,在应该看到的地方没有得到“ Some Name”。

First go to your data model, select the entity you want to add methods to and change the class to something appropriate (I use the entity name with my initials at the beginning). 首先转到您的数据模型,选择要向其添加方法的实体,然后将该类更改为适当的名称(我在开头使用的是名字的缩写)。 Then select New File... from the File menu. 然后从“文件”菜单中选择“新建文件...”。 From there select Managed Object Class (you have to do this while the data model is still the active document or you won't see this option). 从那里选择Managed Object Class(您必须在数据模型仍为活动文档时执行此操作,否则将看不到此选项)。 Step through the file wizard making sure to select the correct entity (Xcode will name the file correctly based on the class you entered earlier). 逐步执行文件向导,确保选择正确的实体(Xcode将根据您先前输入的类正确命名文件)。 Also make sure the Generate accessors and Generate Objective-C 2.0 properties options are selected. 还要确保选中了“生成访问器”和“生成Objective-C 2.0”属性选项。 You should then be able to add any custom methods you want just like any other class. 然后,您应该可以像添加其他任何类一样添加所需的任何自定义方法。 If you need any more help check out http://themikeswan.wordpress.com/2009/05/30/a-core-data-tutorial-part-2-polishing-the-basics/ I wrote this based on Mac OS X, but the concept is the same for iPhone. 如果您需要更多帮助,请访问http://themikeswan.wordpress.com/2009/05/30/a-core-data-tutorial-part-2-polishing-the-basics/我是基于Mac OS X编写的,但iPhone的概念相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM