问题描述
根据文档:
你不应该覆盖init.不鼓励您覆盖 initWithEntity:insertIntoManagedObjectContext:
你应该改用awakeFromInsert 或awakeFromFetch.
and you should instead use awakeFromInsert or awakeFromFetch.
如果我只想将某个属性设置为当前日期或类似日期,这很好,但是如果我想发送另一个对象并根据其信息设置属性怎么办?
This is fine if all I want to do is set some attribute to the current date or similar, but what if I want to send in another object and set attributes based on its information?
例如,在名为Item"的 NSManagedObject 子类中,我想要一个 initFromOtherThing:(Thing *)thing,其中项的名称设置为事物的名称.我想避免只需要记住"每次创建项目后立即设置名称,并且在我决定希望 Item 还基于 Thing 设置另一个默认属性时必须更新十五个不同的控制器类.这些是与模型相关的操作.
For example, in an NSManagedObject subclass called 'Item', I want an initFromOtherThing:(Thing *)thing, in which the item's name is set to that of the thing. I would like to avoid 'just having to remember' to set the name each time immediately after creating the item, and having to update fifteen different controller classes when I decide that I want Item to also set another default attribute based on Thing. These are actions tied to the model.
我打算如何处理这个问题?
How am I meant to handle this?
推荐答案
我认为处理这个问题的最好方法是将 NSManagedObject 子类化,然后创建一个类别来保存您想要添加到对象中的内容.例如几个用于唯一和方便创建的类方法:
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;
}
现在不要直接调用 initWithEntity:insertIntoManagedObjectContext:
只需使用您的便利类方法,例如:
Now don't ever call initWithEntity:insertIntoManagedObjectContext:
directly just use your convenience class method like:
item *newItem = [item itemWithOtherThing: oldThing inContext: currentContext];
这篇关于NSManagedObject 的自定义初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!