A description of an entity in Core Data.
- iOS 3.0+
- macOS 10.4+
- tvOS 9.0+
- watchOS 2.0+
- Core Data
Entities are to managed objects what
Class is to
id, or—to use a database analogy—what tables are to rows. An instance specifies an entity’s name, its properties (its attributes and relationships, expressed by instances of
NSRelationship) and the class by which it is represented.
NSEntity object is associated with a specific class whose instances are used to represent entries in a persistent store in applications using the Core Data Framework. Minimally, an entity description should have:
The name of a managed object class
(If an entity has no managed object class name, it defaults to
You usually define entities in a Managed object modelusing the data modeling tool in Xcode.
NSEntity objects are primarily used by the Core Data Framework for mapping entries in the persistent store to managed objects in the application. You are not likely to interact with them directly unless you are specifically working with models. Like the other major modeling classes,
NSEntity provides you with a user dictionary in which you can store any application-specific information related to the entity.
Editing Entity Descriptions
Entity descriptions are editable until they are used by an object graph manager. This allows you to create or modify them dynamically. However, once a description is used (when the managed object model to which it belongs is associated with a persistent store coordinator), it must not (indeed cannot) be changed. This is enforced at runtime: any attempt to mutate a model or any of its sub-objects after the model is associated with a persistent store coordinator causes an exception to be thrown. If you need to modify a model that is in use, create a copy, modify the copy, and then discard the objects with the old model.
If you want to create an entity hierarchy, you need to consider the relevant API. You can only set an entity’s sub-entities (see
subentities), you cannot set an entity’s super-entity directly. To set a super-entity for a given entity, you must therefore set an array of subentities on that super entity and include the current entity in that array. So, the entity hierarchy needs to be built top-down.
Using Entity Descriptions in Dictionaries
copy method returns an entity such that
NSDictionary copies its keys and requires that keys both conform to the
NSCopying protocol and have the property that
copy returns an object for which
[[object copy] is is true, you should not use entities as keys in a dictionary. Instead, you should either use the entity’s name as the key, or use a map table (
NSMap) with retain callbacks.
NSEntity supports the
NSFast protocol. You can use this to enumerate over an entity’s properties, as illustrated in the following example: