xcode Core Data 中的抽象实体和继承

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11385306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:49:12  来源:igfitidea点击:

Abstract entities and inheritance in Core Data

xcodecore-dataabstract-classnsmanagedobject

提问by cfischer

I have a data model for Formula 1 races with 3 entities:

我有一个包含 3 个实体的一级方程式比赛的数据模型:

  • RacingActor: Abstract entity
  • Pilot: inherits from RacingActor
  • Team: inherits from RacingActor
  • RacingActor:抽象实体
  • Pilot:继承自RacingActor
  • 团队:继承自RacingActor

enter image description here

在此处输入图片说明

If I generate NSManagedObjectsubclasses to represent these entities, the code generated doesn't represent at all this design:

如果我生成NSManagedObject子类来表示这些实体,生成的代码根本不代表这种设计:

  • Everything inherits from NSManagedObject
  • Nothing prevents me from instantiating RacingActor
  • The team property in Pilot is of type NSManagedObjectinstead of Team
  • 一切都继承自 NSManagedObject
  • 没有什么能阻止我实例化 RacingActor
  • Pilot 中的 team 属性是 typeNSManagedObject而不是 Team

Is this the expected behaviour? Am I supposed to fix the code generated by Xcode? Am I missing something?

这是预期的行为吗?我应该修复 Xcode 生成的代码吗?我错过了什么吗?

BTW, I'm using Xcode 4.3.3

顺便说一句,我使用的是 Xcode 4.3.3

采纳答案by fabrice truillot de chambrier

Core Data at the core is an object relational mapping library. Long time ago it was called Entreprise Object Framework, part of WebObjects.

Core Data 的核心是一个对象关系映射库。很久以前,它被称为企业对象框架,是 WebObjects 的一部分。

So yes, the base object for any persistant object managed by Core Data is NSManagedObject, and you can do whatever you want with them.

所以是的,Core Data 管理的任何持久对象的基础对象都是NSManagedObject,你可以对它们做任何你想做的事情。

In your example, Team and Pilot will share a common table, and you'll be able to use queries to retrieve Teams and Pilots at once. That's the idea.

在您的示例中,Team 和 Pilot 将共享一个公共表,您将能够使用查询同时检索 Teams 和 Pilot。这就是想法。

The Objective-C inheritance tree (if you use custom classes) can mirror the model you defined, but it doesn't need to. You can create a custom RacingActorclass, use it as a base class for custom Teamand Pilotclasses, or you can tell the model to use RacingActorfor Teamand Pilotobjects. You can even define a completely unrelated base class (provided NSManagedObjectis a parent, directly or indirectly) for Teamand / or Pilotif you want to.

Objective-C 继承树(如果您使用自定义类)可以镜像您定义的模型,但它不需要。您可以创建自定义RacingActor类,将其用作自定义TeamPilot类的基类,或者您可以告诉模型使用RacingActorforTeamPilot对象。您甚至可以定义一个完全不相关的基类(如果NSManagedObject是直接或间接的父类)Team和/或Pilot如果您愿意。

You are then free to implement the specific behaviors you need in your business logic, either in controllers or in custom data classes.

然后您可以自由地在您的业务逻辑中实现您需要的特定行为,无论是在控制器中还是在自定义数据类中。