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

发布于 2024-08-30 10:19:34 字数 536 浏览 3 评论 0 原文

我有几个核心数据生成的类文件,我想向其中添加自定义方法。我不需要添加任何实例变量。我该怎么做?

我尝试添加一类方法:

// 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”。

I've got a couple of Core Data-generated class files that I'd like to add custom methods to. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ζ澈沫 2024-09-06 10:19:34

首先转到您的数据模型,选择要添加方法的实体,并将类更改为适当的类(我使用以我的名字开头的实体名称)。然后从“文件”菜单中选择“新建文件...”。从那里选择“托管对象类”(您必须在数据模型仍然是活动文档时执行此操作,否则您将看不到此选项)。逐步完成文件向导,确保选择正确的实体(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文