Custom initializer for an NSManagedObject

荒凉一梦 提交于 2019-11-29 12:12:05

I think the best way to handle this is by subclassing the NSManagedObject and then creating a category to hold what you want to add to the object. For example a couple of class methods for uniquing and conveniently creating:

+ (item *) findItemRelatedToOtherThing: (Thing *) existingThing inManagedObjectContext *) context {
    item *foundItem = nil;
    // Do NSFetchRequest to see if this item already exists...
    return foundItem;
}

+ (item *) itemWithOtherThing: (Thing *) existingThing inContext: (NSManagedObjectContext *) context {
    item *theItem;
    if( !(theItem = [self findItemRelatedToOtherThing: existingThing inManagedObjectContext: context]) ) {
        NSLog( @"Creating a new item for Thing %@", existingThing );
        theItem = [NSEntityDescription insertNewObjectForEntityForName: @"item" inManagedObjectContext: context];
        theItem.whateverYouWant = existingThing.whateverItHas;
    }
    return theItem; 
}

Now don't ever call initWithEntity:insertIntoManagedObjectContext: directly just use your convenience class method like:

item *newItem = [item itemWithOtherThing: oldThing inContext: currentContext];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!