我可以向 Core Data 生成的类添加自定义方法吗?
我有几个核心数据生成的类文件,我想向其中添加自定义方法。我不需要添加任何实例变量。我该怎么做?
我尝试添加一类方法:
// 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
但这不起作用。我收到一条编译器消息“-NSManagedObject 可能不会响应‘displayName’”,果然,当我运行应用程序时,我没有在应该看到的地方看到“Some Name”。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先转到您的数据模型,选择要添加方法的实体,并将类更改为适当的类(我使用以我的名字开头的实体名称)。然后从“文件”菜单中选择“新建文件...”。从那里选择“托管对象类”(您必须在数据模型仍然是活动文档时执行此操作,否则您将看不到此选项)。逐步完成文件向导,确保选择正确的实体(Xcode 将根据您之前输入的类正确命名文件)。还要确保选择“生成访问器”和“生成 Objective-C 2.0 属性”选项。然后,您应该能够像添加任何其他类一样添加您想要的任何自定义方法。如果您需要更多帮助,请查看 http://themikeswan.wordpress.com/2009/05/30/a-core-data-tutorial-part-2-polishing-the-basics/ 我是基于 Mac OS 编写的X,但概念对于 iPhone 是相同的。
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). 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). Also make sure the Generate accessors and Generate Objective-C 2.0 properties options are selected. 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.