This project explores the potential of creating CoreData object models from Swift code by applying macros to class and property declarations. It aims to provide an alternative to Xcode's object model editor which:
- unifies specification of object model and custom logic as Swift code;
- enables composition of object models;
- makes property metadata available for tasks such as data import and export;
- simplifies support for non-standard attribute types.
NOTE: This project was implemented prior to the announcement of SwiftData at WWDC23 and has been made redundant by that technology; I'm not claiming originality here, as the idea is rather obvious.
The code is split across the following targets:
- StorableMacros is the library which implements the custom macros
- Storable is the library which defines the core types and exports the custom macros
- StorableTests is the test suite; it provides simple usage examples
ManagedObject is a subclass of NSManagedObject which serves as the abstract base class for entity definitions.
Storable is the protocol which specifies the requirements of supported attribute types.
ManagedPropertyMacro is a protocol describing the requirements of accessor macros used to define managed object properties; AttributeMacro, RelationshipMacro, and FetchedMacro are the conforming implementations which define descriptors for attributes, relationships and fetched properties. Attribute, Relationship and Fetched are custom descriptor types corresponding to the three subclasses of NSPropertyDescription; each is accompanied by a same-named macro declaration which identifies the corresponding macro implementation type.
EntityMacro is a member macro used to aggregate the managed properties of an associated ManagedObject class. The Entity type is a custom entity descriptor corresponding to NSEntityDescription.
Schema is a structure which represents a complete object model and which generates an NSManagedObjectModel.
DataStore is a convenience class which manages a persistent store and provides an NSManagedObjectContext for a given Schema.
An introductory article describes the core mechanics of the system.
A secondary article describes the impact on persistent store migration.