Skip to content

Instantly share code, notes, and snippets.

@ashevin
Created May 29, 2017 05:22
Show Gist options
  • Save ashevin/6465a6993a77fbd84fbf04b07d931c6a to your computer and use it in GitHub Desktop.
Save ashevin/6465a6993a77fbd84fbf04b07d931c6a to your computer and use it in GitHub Desktop.
NSManagedObject subclasses
Core Data describes objects as entities, with relationships between entities. At runtime, Core Data will create an instance of NSManagedObject, which will allow access to the properties of the entity. Functionally, an instance of NSManagedObject acts much like NSDictionary, wherein a key matching the name of one of the entity's properties is used to access that property's value, or to change it.
Using raw NSManagedObjects are a poor choice in any serious application. There's no type-safety. Access to properties is predicated on correctly spelling the property names, and generally all the downsides of stringly-typed data and properties. For this reason, Core Data allows the model to specify subclasses of NSManagedObject, one per entity, which will be created when Core Data needs to present an entity instance at runtime. These subclasses specify strongly-typed properties, matching the property names in the entity definition. Such classes may also contain other properties, not backed or managed by Core Data. These subclasses are no different than any other class, in terms of capability.
The basic mechanism that Core Data uses for NSManagedObject subclasses is as follows. Instead of synthesizing or implementing the getters and setters for core data properties, one specifies that the properties are dynamic. (In Swift, one uses @NSManaged to achieve the same effect.) What dynamic means in the context of Objective-C is that the compiler is being informed that the implementation for the getter and setter will be provided at runtime. How this happens is of no concern to the compiler, nor is it of much concern to users of Core Data.
When an NSManagedObject subclass's property is accessed, the base NSManagedObject class has code which intercepts the attempt and uses its internal, dictionary-like, representation to find and manipulate the property's value. This intercept only takes place for properties specified as dynamic (@NSManaged). Because the intercept happens at runtime, and only when methods (getters or setters) are invoked on the properties, it is perfectly legal to only define a subset of the properties the entity may contain. Other properties of the entity are simply not available as properties via the syntax of the language.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment