如何扩展核心数据实体类 [英] How to extend core data entity classes

查看:104
本文介绍了如何扩展核心数据实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用Xcode生成的NSManagedObject的子类。我为这些类编写了一些验证代码( validateForInsert:),但是每次我更新数据模型并重新生成子类时,所有这些验证代码都会消失。有人建议我使用类别来扩展这些类别,而不是在其中编写代码,但是根据Apple的文档,使用类别覆盖方法是非常不好的做法,并且可能导致不确定的行为。

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.

我也尝试将那些生成的类子类化。我有一个名为 DBEntityOne 的生成类,其子类名为 EntityOne 。 EntityOne与EntityTwo具有一对一关系,由 DBEntityTwo (生成)和 EntityTwo 表示。但是,每当我尝试获取与EntityOne实例关联的EntityTwo时,得到的就是 DBEntityTwo 而不是 EntityTwo

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. 您可以使用类别(Objective-C)或扩展(Swift)扩展实体类。尽管有苹果公司的警告,但这通常是安全的。至少,我使用实体类的扩展没有问题。

  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.

一旦有了生成的类,就很容易手动向其添加属性用于新的实体字段。您不需要仅生成少量代码就可以重新生成类文件。

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.

如果使用的是源代码控制系统,则可以重新生成类,然后将重新生成的类与版本化的类合并。这样一来,您就可以轻松保留自定义代码,同时获得所生成代码的好处。

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.

这篇关于如何扩展核心数据实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆