views:

79

answers:

1

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.

+1  A: 

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.

theMikeSwan
This is the "correct" way to do this. However, it can become difficult to manage the amalgam of machine- and human-generated code. I highly recommend using Wolf Rentzsch's **mogenerator** (http://rentzsch.github.com/mogenerator/). It automates this repetitive and error prone task and adds some very nice automated features to the custom class like (un-)boxing of NSNumbers and such.
Matt B.