How to extend core data entity classes

别等时光非礼了梦想. 提交于 2019-12-12 05:29:11

问题


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.



来源:https://stackoverflow.com/questions/28291182/how-to-extend-core-data-entity-classes

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