开发者

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

I've got a couple of Core Data-gene开发者_如何学运维rated 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜