How to extend core data entity classes

2019-08-28 10:42发布

问题:

I have some subclasses of NSManagedObject generated using Xcode. I wrote some validation codes (validateForInsert:) to those classes, but every time I update the data model and regenerate the subclasses, all those validation codes disappear. Some people suggest me to use categories to extend these classes instead of writing codes in it, but according to apple's document, overriding methods with categories is a very bad practice and can lead to undefined behaviour.

I also tried to subclass those generated classes. I have a generated class called DBEntityOne and its subclass is called EntityOne. EntityOne has an one-to-one relationship with EntityTwo, which is represented by DBEntityTwo(generated) and EntityTwo. However, whenever I try to get the EntityTwo associated with an EntityOne instance, what I get is a DBEntityTwo instead of EntityTwo.

So what should I do? Should I give up the automatic code generation and write all the entity classes by myself?

回答1:

Some suggestions...

  1. You can extend the entity classes using categories (Objective-C) or extensions (Swift). Despite Apple's warnings, this is generally safe. At least, I've worked with extensions to entity classes with no issues.

  2. Once you have the generated classes, it's pretty easy to add properties to them manually for the new entity fields. You don't need to regenerate the class files just to get that little bit of code.

  3. If you are using a source control system, you can regenerate the classes, then merge the regenerated classes with your versioned classes. This easily allows you to keep your custom code, while getting the benefit of the generated code.