Carlos
Carlos

Reputation: 1133

Custom init for a NSManagedObject subclass

How can I code a custom init for NSManagedObject subclass? I would like something like initItemWithName:Volume: for instance. Where Item is a NSManagedObject subclass with two attributes, name and volume.

Upvotes: 5

Views: 5136

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

Carlos,

As Nenad Mihajlovic suggested you could create a category for this.

So, for example, if you have an Item class, you could create a category called Item+Management and put the creation code there. Here you can find a simple example.

// .h

@interface Item (Management)

+ (Item*)itemWithName:(NSString *)theName volume:(NSNumber*)theVolume inManagedObjectContext:(NSManagedObjectContext *)context;

@end

// .m

+ (Item*)itemWithName:(NSString *)theName volume:(NSNumber*)theVolume inManagedObjectContext:(NSManagedObjectContext *)context
{
    Item* item = (Item*)[NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:context];
    theItem.name = theName;
    theItem.volume = theVolume;

    return item;
}

When you want to create a new Item, do an import like

#import "Item+Management.h"

and use like this

Item* item = [Item itemWithName:@"test" volume:[NSNumber numberWithInt:10] inManagedObjectContext:yourContext];
// do what you want with item...

This approach is very flexible and very easy to maintain during the app developing.

You can find further info at Stanford Course Lecture 14 code sample. In addition, see also free videos on iTunes by Stanford (if you have an Apple ID).

Hope that helps.

P.S. For the sake of simplicity, I suppose name is a NSString and volume is a NSNumber. For volume it could be better to use NSDecimalNumber type.

Upvotes: 6

Related Questions