简体   繁体   English

向核心数据类添加自定义方法

[英]Adding custom methods to core data classes

What is the best way to add custom methods to my core data generated classes? 向我的核心数据生成类添加自定义方法的最佳方法是什么?

For example, say I have a "Person" entity with properties "firstname" and "lastname". 例如,假设我有一个“Person”实体,其属性为“firstname”和“lastname”。 I wish to add a "fullname" method, which returns a concatenation of the firstname and lastname properties. 我希望添加一个“fullname”方法,该方法返回firstname和lastname属性的串联。

I could add the method to the generated .h and .m files, but this would be difficult to maintain during development when my entities may still change. 我可以将方法添加到生成的.h和.m文件中,但是在开发期间,当我的实体可能仍然发生变化时,这很难维护。 Recreating the .h and .m file would overwrite these changes. 重新创建.h和.m文件将覆盖这些更改。 Another idea is to subclass the generated class and add the methods there. 另一个想法是子类化生成的类并在那里添加方法。

Is there a better way? 有没有更好的办法?

I find that the best way to add custom methods that aren't directly tied to data properties is to use a category. 我发现添加与数据属性没有直接关联的自定义方法的最佳方法是使用类别。 This generally works best if you create your Core Data entities as their own subclasses of NSManagedObject in the data modeler, but it can work without that as well. 如果您在数据建模器中将Core Data实体创建为NSManagedObject的子类,这通常最有效,但它也可以在没有它的情况下工作。 This way all the machine generated code can stay in the main .h and .m files, and all your custom code goes in the .h and .m for your category on that class. 这样,所有机器生成的代码都可以保留在主.h和.m文件中,并且所有自定义代码都以.h和.m的形式存在于该类的类别中。

I'd recommend adding these methods to your custom NSManagedObject subclass. 我建议将这些方法添加到自定义NSManagedObject子类中。 If you're worried about maintaining accessors as your data model changes, while preserving your custom methods, I'd suggest looking to "Wolf" Rentzsch's mogenerator . 如果您担心在数据模型发生变化时维护访问器,同时保留自定义方法,我建议您选择“Wolf”Rentzsch的发电机 Many people swear by this tool for just this purpose. 很多人为此目的发誓这个工具。

You create your own subclass of NSManagedObject for the entities. 您可以为实体创建自己的NSManagedObject子类。

Better explained in the NSManagedObject documentation 更好地解释了NSManagedObject文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM