Custom init for a subclass of NSManagedObject

How can I encode custom initto NSManagedObjectsubclass? For example, I would like something like that initItemWithName:Volume:. Where Itemis the subclass NSManagedObjectwith two attributes, nameand volume.

+5
source share
1 answer

Carlos

As Nenad Mikhailovich proposed creating a category for this.

So, for example, if you have a class Item, you can create a category with a name Item+Managementand 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;
}

If you want to create a new item, do the import, for example

#import "Item+Management.h"

and use it like

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

.

14. , . iTunes ( Apple ID).

, .

P.S. , name NSString, volume - NSNumber. volume NSDecimalNumber.

+6

All Articles