我认为处理这个问题的最好方法是继承 NSManagedObject,然后创建一个类别来保存你想要添加到对象的内容。例如,一些用于唯一且方便地创建的类方法:
+ (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;
}
现在永远不要initWithEntity:insertIntoManagedObjectContext:
直接调用,只需使用您的便利类方法,例如:
item *newItem = [item itemWithOtherThing: oldThing inContext: currentContext];