{"id":945,"url":"https://github.com/JohnEstropia/CoreStore","last_synced_at":"2025-08-06T13:32:08.732Z","repository":{"id":24585495,"uuid":"27993573","full_name":"JohnEstropia/CoreStore","owner":"JohnEstropia","description":"Unleashing the real power of Core Data with the elegance and safety of Swift","archived":false,"fork":false,"pushed_at":"2024-10-31T07:37:58.000Z","size":14985,"stargazers_count":4053,"open_issues_count":94,"forks_count":260,"subscribers_count":72,"default_branch":"develop","last_synced_at":"2025-08-01T18:18:46.712Z","etag":null,"topics":["carthage","cocoapods","core-data","coredata","swift","swift-package-manager"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohnEstropia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["JohnEstropia"]}},"created_at":"2014-12-14T12:26:04.000Z","updated_at":"2025-07-29T23:56:48.000Z","dependencies_parsed_at":"2024-04-27T20:40:25.278Z","dependency_job_id":"8825833a-b172-4e22-b8e9-b76c7ff23871","html_url":"https://github.com/JohnEstropia/CoreStore","commit_stats":{"total_commits":1017,"total_committers":37,"mean_commits":"27.486486486486488","dds":0.06784660766961648,"last_synced_commit":"104def4611b8f8c2067903b589d01d198d51e6d6"},"previous_names":[],"tags_count":102,"template":false,"template_full_name":null,"purl":"pkg:github/JohnEstropia/CoreStore","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnEstropia%2FCoreStore","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnEstropia%2FCoreStore/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnEstropia%2FCoreStore/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnEstropia%2FCoreStore/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohnEstropia","download_url":"https://codeload.github.com/JohnEstropia/CoreStore/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnEstropia%2FCoreStore/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268299453,"owners_count":24228478,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-01T02:00:08.611Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["carthage","cocoapods","core-data","coredata","swift","swift-package-manager"],"created_at":"2024-01-05T20:15:35.206Z","updated_at":"2025-08-06T13:32:07.385Z","avatar_url":"https://github.com/JohnEstropia.png","language":"Swift","funding_links":["https://github.com/sponsors/JohnEstropia"],"categories":["Core Data","Libs","Swift","HarmonyOS","Data and Storage","Data Management [🔝](#readme)"],"sub_categories":["Linter","Data Management","Other free courses","Windows Manager"],"readme":"\u003cp align=\"center\"\u003e\n\u003cimg alt=\"CoreStore\" src=\"https://github.com/JohnEstropia/CoreStore/raw/develop/CoreStore.png\" width=614 /\u003e\n\u003cbr /\u003e\n\u003cbr /\u003e\nUnleashing the real power of Core Data with the elegance and safety of Swift\n\u003cbr /\u003e\n\u003cbr /\u003e\n\u003ca href=\"https://app.bitrise.io/app/e736852157296019#/builds\"\u003e\u003cimg alt=\"Build Status\" src=\"https://img.shields.io/bitrise/e736852157296019/master.svg?label=build\u0026token=vhgAmaiF3tWZoQyFLkKM7g\u0026logo=bitrise\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/JohnEstropia/CoreStore/commits\"\u003e\u003cimg alt=\"Last Commit\" src=\"https://img.shields.io/github/last-commit/johnestropia/corestore.svg?style=flat\" /\u003e\u003c/a\u003e\n\u003ca href=\"http://cocoadocs.org/docsets/CoreStore\"\u003e\u003cimg alt=\"Platform\" src=\"https://img.shields.io/cocoapods/p/CoreStore.svg?style=flat\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://raw.githubusercontent.com/JohnEstropia/CoreStore/master/LICENSE\"\u003e\u003cimg alt=\"License\" src=\"https://img.shields.io/cocoapods/l/CoreStore.svg?style=flat\" /\u003e\u003c/a\u003e\n\u003cbr /\u003e\u003cbr /\u003eDependency managers\u003cbr /\u003e\n\u003ca href=\"https://cocoapods.org/pods/CoreStore\"\u003e\u003cimg alt=\"Cocoapods compatible\" src=\"https://img.shields.io/cocoapods/v/CoreStore.svg?style=flat\u0026label=Cocoapods\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/Carthage/Carthage\"\u003e\u003cimg alt=\"Carthage compatible\" src=\"https://img.shields.io/badge/Carthage-compatible-16a085.svg?style=flat\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://swift.org/source-compatibility/#current-list-of-projects\"\u003e\u003cimg alt=\"Swift Package Manager compatible\" src=\"https://img.shields.io/badge/Swift_Package_Manager-compatible-orange.svg?style=flat\" /\u003e\u003c/a\u003e\n\u003cbr /\u003e\u003cbr /\u003eContact\u003cbr /\u003e\n\u003ca href=\"http://swift-corestore-slack.herokuapp.com/\"\u003e\u003cimg alt=\"Join us on Slack!\" src=\"http://swift-corestore-slack.herokuapp.com/badge.svg?logo=slack\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://twitter.com/JohnEstropia\"\u003e\u003cimg alt=\"Reach me on Twitter!\" src=\"https://img.shields.io/badge/twitter-%40JohnEstropia-3498db.svg?logo=twitter\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/sponsors/JohnEstropia\"\u003e\u003cimg alt=\"Sponsor\" src=\"https://img.shields.io/badge/%E2%9D%A4-Sponsor-ff69bf\"\u003e\u003c/a\u003e\n\u003cbr /\u003e\n\u003c/p\u003e\n\n* **Swift 5.9:** iOS 16.0+ / macOS 13.0+ / watchOS 9.0+ / tvOS 16.0+\n* Previously supported Swift versions: [Swift 5.4](https://github.com/JohnEstropia/CoreStore/tree/8.0.1), [Swift 5.3](https://github.com/JohnEstropia/CoreStore/tree/7.3.1), [Swift 5.7](https://github.com/JohnEstropia/CoreStore/tree/9.1.0)\n\nUpgrading from previous CoreStore versions? Check out the [🆕 features](#features) and make sure to read the [Change logs](https://github.com/JohnEstropia/CoreStore/releases).\n\nCoreStore is part of the [Swift Source Compatibility projects](https://swift.org/source-compatibility/#current-list-of-projects).\n\n## Contents\n\n- [TL;DR (a.k.a. sample codes)](#tldr-aka-sample-codes)\n- [Why use CoreStore?](#why-use-corestore)\n- [Architecture](#architecture)\n- CoreStore Tutorials (All of these have demos in the **Demo** app project!)\n    - [Setting up](#setting-up)\n        - [In-memory store](#in-memory-store)\n        - [Local store](#local-store)\n    - [Migrations](#migrations)\n        - [Declaring model versions](#declaring-model-versions)\n        - [Starting migrations](#starting-migrations)\n        - [Progressive migrations](#progressive-migrations)\n        - [Forecasting migrations](#forecasting-migrations)\n        - [Custom migrations](#custom-migrations)\n    - [Saving and processing transactions](#saving-and-processing-transactions)\n        - [Transaction types](#transaction-types)\n            - [Asynchronous transactions](#asynchronous-transactions)\n            - [Synchronous transactions](#synchronous-transactions)\n            - [Unsafe transactions](#unsafe-transactions)\n        - [Creating objects](#creating-objects)\n        - [Updating objects](#updating-objects)\n        - [Deleting objects](#deleting-objects)\n        - [Passing objects safely](#passing-objects-safely)\n    - [Importing data](#importing-data)\n    - [Fetching and querying](#fetching-and-querying)\n        - [`From` clause](#from-clause)\n        - [Fetching](#fetching)\n            - [`Where` clause](#where-clause)\n            - [`OrderBy` clause](#orderby-clause)\n            - [`Tweak` clause](#tweak-clause)\n        - [Querying](#querying)\n            - [`Select\u003cT\u003e` clause](#selectt-clause)\n            - [`GroupBy` clause](#groupby-clause)\n    - [Logging and error reporting](#logging-and-error-reporting)\n    - [Observing changes and notifications](#observing-changes-and-notifications)\n        - [Observe a single property](#observe-a-single-property)\n        - [Observe a single object's updates](#observe-a-single-objects-updates)\n        - [Observe a single object's per-property updates](#observe-a-single-objects-per-property-updates)\n        - [Observe a diffable list](#observe-a-diffable-list)\n        - [Observe detailed list changes](#observe-detailed-list-changes)\n    - [Type-safe `CoreStoreObject`s](#type-safe-corestoreobjects)\n        - [New `@Field` Property Wrapper syntax](#new-field-property-wrapper-syntax)\n            - [`@Field.Stored` ](#fieldstored)\n            - [`@Field.Virtual` ](#fieldvirtual)\n            - [`@Field.Coded` ](#fieldcoded)\n            - [`@Field.Relationship` ](#fieldrelationship)\n            - [`@Field` usage notes](#field-usage-notes)\n        - [`VersionLock`s](#versionlocks)\n    - [Reactive Programming](#reactive-programming)\n        - [RxSwift](#rxswift)\n        - 🆕[Combine](#combine)\n            - 🆕[`DataStack.reactive`](#datastackreactive)\n            - 🆕[`ListPublisher.reactive`](#listpublisherreactive)\n            - 🆕[`ObjectPublisher.reactive`](#objectpublisherreactive)\n    - 🆕[SwiftUI Utilities](#swiftui-utilities)\n        - 🆕[SwiftUI Views`](#swiftui-views)\n            - 🆕[`ListReader`](#listreader)\n            - 🆕[`ObjectReader`](#objectreader)\n        - 🆕[SwiftUI Property Wrappers](#swiftui-property-wrappers)\n            - 🆕[`ListState`](#liststate)\n            - 🆕[`ObjectState`](#objectstate)\n        - 🆕[SwiftUI Extensions](#swiftui-extensions)\n            - 🆕[`ForEach`](#foreach)\n- [Roadmap](#roadmap)\n- [Installation](#installation)\n- [Changesets](#changesets)\n- [Contact](#contact)\n- [Who uses CoreStore?](#who-uses-corestore)\n- [License](#license)\n\n\n\n## TL;DR (a.k.a. sample codes)\n\nPure-Swift models:\n```swift\nclass Person: CoreStoreObject {\n    @Field.Stored(\"name\")\n    var name: String = \"\"\n    \n    @Field.Relationship(\"pets\", inverse: \\Dog.$master)\n    var pets: Set\u003cDog\u003e\n}\n```\n(Classic `NSManagedObject`s also supported)\n\nSetting-up with progressive migration support:\n```swift\ndataStack = DataStack(\n    xcodeModelName: \"MyStore\",\n    migrationChain: [\"MyStore\", \"MyStoreV2\", \"MyStoreV3\"]\n)\n```\n\nAdding a store:\n```swift\ndataStack.addStorage(\n    SQLiteStore(fileName: \"MyStore.sqlite\"),\n    completion: { (result) -\u003e Void in\n        // ...\n    }\n)\n```\n\nStarting transactions:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let person = transaction.create(Into\u003cPerson\u003e())\n        person.name = \"John Smith\"\n        person.age = 42\n    },\n    completion: { (result) -\u003e Void in\n        switch result {\n        case .success: print(\"success!\")\n        case .failure(let error): print(error)\n        }\n    }\n)\n```\n\nFetching objects (simple):\n```swift\nlet people = try dataStack.fetchAll(From\u003cPerson\u003e())\n```\n\nFetching objects (complex):\n```swift\nlet people = try dataStack.fetchAll(\n    From\u003cPerson\u003e()\n        .where(\\.age \u003e 30),\n        .orderBy(.ascending(\\.name), .descending(.\\age)),\n        .tweak({ $0.includesPendingChanges = false })\n)\n```\n\nQuerying values:\n```swift\nlet maxAge = try dataStack.queryValue(\n    From\u003cPerson\u003e()\n        .select(Int.self, .maximum(\\.age))\n)\n```\n\nBut really, there's a reason I wrote this huge *README*. Read up on the details!\n\nCheck out the **Demo** app project for sample codes as well!\n\n\n## Why use CoreStore?\n\nCoreStore was (and is) heavily shaped by real-world needs of developing data-dependent apps. It enforces safe and convenient Core Data usage while letting you take advantage of the industry's encouraged best practices.\n\n### Features\n\n- **🆕[SwiftUI](#swiftui-utilities) and [Combine](#combine) API utilities.** `ListPublisher`s and `ObjectPublisher`s now have their `@ListState` and `@ObjectState` SwiftUI property wrappers. Combine `Publisher` s are also available through the `ListPublisher.reactive`, `ObjectPublisher.reactive`, and `DataStack.reactive` namespaces.\n- **Backwards-portable [DiffableDataSources implementation](#observe-a-diffable-list)!** `UITableViews` and `UICollectionViews` now have a new ally: `ListPublisher`s provide diffable snapshots that make reloading animations very easy and very safe. Say goodbye to `UITableViews` and `UICollectionViews` reload errors!\n- **💎Tight design around Swift’s code elegance and type safety.** CoreStore fully utilizes Swift's community-driven language features.\n- **🚦Safer concurrency architecture.** CoreStore makes it hard to fall into common concurrency mistakes. The main `NSManagedObjectContext` is strictly read-only, while all updates are done through serial *transactions*. *(See [Saving and processing transactions](#saving-and-processing-transactions))*\n- **🔍Clean fetching and querying API.** Fetching objects is easy, but querying for raw aggregates (`min`, `max`, etc.) and raw property values is now just as convenient. *(See [Fetching and querying](#fetching-and-querying))*\n- **🔭Type-safe, easy to configure observers.** You don't have to deal with the burden of setting up `NSFetchedResultsController`s and KVO. As an added bonus, list and object observable types all support multiple observers. This means you can have multiple view controllers efficiently share a single resource! *(See [Observing changes and notifications](#observing-changes-and-notifications))*\n- **📥Efficient importing utilities.** Map your entities once with their corresponding import source (JSON for example), and importing from *transactions* becomes elegant. Uniquing is also done with an efficient find-and-replace algorithm. *(See [Importing data](#importing-data))*\n- **🗑Say goodbye to *.xcdatamodeld* files!** While CoreStore supports `NSManagedObject`s, it offers `CoreStoreObject` whose subclasses can declare type-safe properties all in Swift code without the need to maintain separate resource files for the models. As bonus, these special properties support custom types, and can be used to create type-safe keypaths and queries. *(See [Type-safe `CoreStoreObject`s](#type-safe-corestoreobjects))*\n- **🔗Progressive migrations.** No need to think how to migrate from all previous model versions to your latest model. Just tell the `DataStack` the sequence of version strings (`MigrationChain`s) and CoreStore will automatically use progressive migrations when needed. *(See [Migrations](#migrations))*\n- **Easier custom migrations.** Say goodbye to *.xcmappingmodel* files; CoreStore can now infer entity mappings when possible, while still allowing an easy way to write custom mappings. *(See [Migrations](#migrations))*\n- **📝Plug-in your own logging framework.** Although a default logger is built-in, all logging, asserting, and error reporting can be funneled to `CoreStoreLogger` protocol implementations. *(See [Logging and error reporting](#logging-and-error-reporting))*\n- **⛓Heavy support for multiple persistent stores per data stack.** CoreStore lets you manage separate stores in a single `DataStack`, just the way *.xcdatamodeld* configurations are designed to. CoreStore will also manage one stack by default, but you can create and manage as many as you need. *(See [Setting up](#setting-up))*\n- **🎯Free to name entities and their class names independently.** CoreStore gets around a restriction with other Core Data wrappers where the entity name should be the same as the `NSManagedObject` subclass name. CoreStore loads entity-to-class mappings from the managed object model file, so you can assign independent names for the entities and their class names.\n- **📙Full Documentation.** No magic here; all public classes, functions, properties, etc. have detailed *Apple Docs*. This *README* also introduces a lot of concepts and explains a lot of CoreStore's behavior.\n- **ℹ️Informative (and pretty) logs.** All CoreStore and Core Data-related types now have very informative and pretty print outputs! *(See [Logging and error reporting](#logging-and-error-reporting))*\n- **🛡More extensive Unit Tests.** Extending CoreStore is safe without having to worry about breaking old behavior.\n\n*Have ideas that may benefit other Core Data users? [Feature Request](https://github.com/JohnEstropia/CoreStore/issues)s are welcome!*\n\n\n\n## Architecture\nFor maximum safety and performance, CoreStore will enforce coding patterns and practices it was designed for. (Don't worry, it's not as scary as it sounds.) But it is advisable to understand the \"magic\" of CoreStore before you use it in your apps.\n\nIf you are already familiar with the inner workings of CoreData, here is a mapping of `CoreStore` abstractions:\n\n| *Core Data* | *CoreStore* |\n| --- | --- |\n| `NSPersistentContainer`\u003cbr /\u003e(.xcdatamodeld file) | `DataStack` |\n| `NSPersistentStoreDescription`\u003cbr /\u003e(\"Configuration\"s in the .xcdatamodeld file) | `StorageInterface` implementations\u003cbr /\u003e(`InMemoryStore`, `SQLiteStore`) |\n| `NSManagedObjectContext` | `BaseDataTransaction` subclasses\u003cbr /\u003e(`SynchronousDataTransaction`, `AsynchronousDataTransaction`, `UnsafeDataTransaction`) |\n\nA lot of Core Data wrapper libraries set up their `NSManagedObjectContext`s this way:\n\n\u003cimg src=\"https://cloud.githubusercontent.com/assets/3029684/16707160/984ef25c-4600-11e6-869f-8db7d2c63668.png\" alt=\"nested contexts\" height=380 /\u003e\n\nNesting saves from child context to the root context ensures maximum data integrity between contexts without blocking the main queue. But \u003ca href=\"http://floriankugler.com/2013/04/29/concurrent-core-data-stack-performance-shootout/\"\u003ein reality\u003c/a\u003e, merging contexts is still by far faster than saving contexts. CoreStore's `DataStack` takes the best of both worlds by treating the main `NSManagedObjectContext` as a read-only context (or \"viewContext\"), and only allows changes to be made within *transactions* on the child context:\n\n\u003cimg src=\"https://cloud.githubusercontent.com/assets/3029684/16707161/9adeb962-4600-11e6-8bc8-4ec85764dba4.png\" alt=\"nested contexts and merge hybrid\" height=292 /\u003e\n\nThis allows for a butter-smooth main thread, while still taking advantage of safe nested contexts.\n\n\n\n## Setting up\nThe simplest way to initialize CoreStore is to add a default store to the default stack:\n```swift\ntry CoreStoreDefaults.dataStack.addStorageAndWait()\n```\nThis one-liner does the following:\n- Triggers the lazy-initialization of `CoreStoreDefaults.dataStack` with a default `DataStack`\n- Sets up the stack's `NSPersistentStoreCoordinator`, the root saving `NSManagedObjectContext`, and the read-only main `NSManagedObjectContext`\n- Adds an `SQLiteStore` in the *\"Application Support/\u003cbundle id\u003e\"* directory (or the *\"Caches/\u003cbundle id\u003e\"* directory on tvOS) with the file name *\"[App bundle name].sqlite\"*\n- Creates and returns the `NSPersistentStore` instance on success, or an `NSError` on failure\n\nFor most cases, this configuration is enough as it is. But for more hardcore settings, refer to this extensive example:\n```swift\nlet dataStack = DataStack(\n    xcodeModelName: \"MyModel\", // loads from the \"MyModel.xcdatamodeld\" file\n    migrationChain: [\"MyStore\", \"MyStoreV2\", \"MyStoreV3\"] // model versions for progressive migrations\n)\nlet migrationProgress = dataStack.addStorage(\n    SQLiteStore(\n        fileURL: sqliteFileURL, // set the target file URL for the sqlite file\n        configuration: \"Config2\", // use entities from the \"Config2\" configuration in the .xcdatamodeld file\n        localStorageOptions: .recreateStoreOnModelMismatch // if migration paths cannot be resolved, recreate the sqlite file\n    ),\n    completion: { (result) -\u003e Void in\n        switch result {\n        case .success(let storage):\n            print(\"Successfully added sqlite store: \\(storage)\")\n        case .failure(let error):\n            print(\"Failed adding sqlite store with error: \\(error)\")\n        }\n    }\n)\n\nCoreStoreDefaults.dataStack = dataStack // pass the dataStack to CoreStore for easier access later on\n```\n\n\u003e 💡If you have never heard of \"Configurations\", you'll find them in your *.xcdatamodeld* file\n\u003e \u003cimg src=\"https://cloud.githubusercontent.com/assets/3029684/8333192/e52cfaac-1acc-11e5-9902-08724f9f1324.png\" alt=\"xcode configurations screenshot\" height=212 /\u003e\n\nIn our sample code above, note that you don't need to do the `CoreStoreDefaults.dataStack = dataStack` line. You can just as well hold a reference to the `DataStack` like below and call all its instance methods directly:\n```swift\nclass MyViewController: UIViewController {\n    let dataStack = DataStack(xcodeModelName: \"MyModel\") // keep reference to the stack\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        do {\n            try self.dataStack.addStorageAndWait(SQLiteStore.self)\n        }\n        catch { // ...\n        }\n    }\n    func methodToBeCalledLaterOn() {\n        let objects = self.dataStack.fetchAll(From\u003cMyEntity\u003e())\n        print(objects)\n    }\n}\n```\n\n\u003e 💡By default, CoreStore will initialize `NSManagedObject`s from *.xcdatamodeld* files, but you can create models completely from source code using `CoreStoreObject`s and `CoreStoreSchema`.  To use this feature, refer to [Type-safe `CoreStoreObject`s](#type-safe-corestoreobjects).\n\nNotice that in our previous examples, `addStorageAndWait(_:)` and `addStorage(_:completion:)` both accept either `InMemoryStore`, or `SQLiteStore`. These implement the `StorageInterface` protocol.\n\n### In-memory store\nThe most basic `StorageInterface` concrete type is the `InMemoryStore`, which just stores objects in memory. Since `InMemoryStore`s always start with a fresh empty data, they do not need any migration information.\n```swift\ntry dataStack.addStorageAndWait(\n    InMemoryStore(\n        configuration: \"Config2\" // optional. Use entities from the \"Config2\" configuration in the .xcdatamodeld file\n    )\n)\n```\nAsynchronous variant:\n```swift\ntry dataStack.addStorage(\n    InMemoryStore(\n        configuration: \"Config2\n    ),\n    completion: { storage in\n        // ...\n    }\n)\n```\n\n(A reactive-programming variant of this method is explained in detail in the section on [`DataStack` Combine publishers](#datastackreactive))\n\n### Local Store\nThe most common `StorageInterface` you will probably use is the `SQLiteStore`, which saves data in a local SQLite file.\n```swift\nlet migrationProgress = dataStack.addStorage(\n    SQLiteStore(\n        fileName: \"MyStore.sqlite\",\n        configuration: \"Config2\", // optional. Use entities from the \"Config2\" configuration in the .xcdatamodeld file\n        migrationMappingProviders: [Bundle.main], // optional. The bundles that contain required .xcmappingmodel files\n        localStorageOptions: .recreateStoreOnModelMismatch // optional. Provides settings that tells the DataStack how to setup the persistent store\n    ),\n    completion: { /* ... */ }\n)\n```\nRefer to the *SQLiteStore.swift* source documentation for detailed explanations for each of the default values.\n\nCoreStore can decide the default values for these properties, so `SQLiteStore`s can be initialized with no arguments:\n```swift\ntry dataStack.addStorageAndWait(SQLiteStore())\n```\n\n(The asynchronous variant of this method is explained further in the next section on [Migrations](#starting-migrations), and a reactive-programming variant in the section on [`DataStack` Combine publishers](#datastackreactive))\n\nThe file-related properties of `SQLiteStore` are actually requirements of another protocol that it implements, the `LocalStorage` protocol:\n```swift\npublic protocol LocalStorage: StorageInterface {\n    var fileURL: NSURL { get }\n    var migrationMappingProviders: [SchemaMappingProvider] { get }\n    var localStorageOptions: LocalStorageOptions { get }\n    func dictionary(forOptions: LocalStorageOptions) -\u003e [String: AnyObject]?\n    func cs_eraseStorageAndWait(metadata: [String: Any], soureModelHint: NSManagedObjectModel?) throws\n}\n```\nIf you have custom `NSIncrementalStore` or `NSAtomicStore` subclasses, you can implement this protocol and use it similarly to `SQLiteStore`.\n\n\n## Migrations\n\n### Declaring model versions\nModel versions are now expressed as a first-class protocol, `DynamicSchema`. CoreStore currently supports the following schema classes:\n- **`XcodeDataModelSchema`**: a model version with entities loaded from a *.xcdatamodeld* file.\n- **`CoreStoreSchema`**: a model version created with `CoreStoreObject` entities. *(See [Type-safe `CoreStoreObject`s](#type-safe-corestore-objects))*\n- **`UnsafeDataModelSchema`**: a model version created with an existing `NSManagedObjectModel` instance.\n\nAll the `DynamicSchema` for all model versions are then collected within a single `SchemaHistory` instance, which is then handed to the `DataStack`. Here are some common use cases:\n\n**Multiple model versions grouped in a *.xcdatamodeld* file (Core Data standard method)**\n```swift\nCoreStoreDefaults.dataStack = DataStack(\n    xcodeModelName: \"MyModel\",\n    bundle: Bundle.main,\n    migrationChain: [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\"]\n)\n```\n\n**`CoreStoreSchema`-based model version (No *.xcdatamodeld* file needed)**\n*(For more details, see also [Type-safe `CoreStoreObject`s](#type-safe-corestore-objects))*\n```swift\nclass Animal: CoreStoreObject {\n    // ...\n}\nclass Dog: Animal {\n    // ...\n}\nclass Person: CoreStoreObject {\n    // ...\n}\n\nCoreStoreDefaults.dataStack = DataStack(\n    CoreStoreSchema(\n        modelVersion: \"V1\",\n        entities: [\n            Entity\u003cAnimal\u003e(\"Animal\", isAbstract: true),\n            Entity\u003cDog\u003e(\"Dog\"),\n            Entity\u003cPerson\u003e(\"Person\")\n        ]\n    )\n)\n```\n\n**Models in a *.xcdatamodeld* file during past app versions, but migrated to the new `CoreStoreSchema` method**\n```swift\nclass Animal: CoreStoreObject {\n    // ...\n}\nclass Dog: Animal {\n    // ...\n}\nclass Person: CoreStoreObject {\n    // ...\n}\n\nlet legacySchema = XcodeDataModelSchema.from(\n    modelName: \"MyModel\", // .xcdatamodeld name\n    bundle: bundle,\n    migrationChain: [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\"]\n)\nlet newSchema = CoreStoreSchema(\n    modelVersion: \"V1\",\n    entities: [\n        Entity\u003cAnimal\u003e(\"Animal\", isAbstract: true),\n        Entity\u003cDog\u003e(\"Dog\"),\n        Entity\u003cPerson\u003e(\"Person\")\n    ]\n)\nCoreStoreDefaults.dataStack = DataStack(\n    schemaHistory: SchemaHistory(\n        legacySchema + [newSchema],\n        migrationChain: [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\", \"V1\"] \n    )\n)   \n```\n\n**`CoreStoreSchema`-based model versions with progressive migration**\n```swift\ntypealias Animal = V2.Animal\ntypealias Dog = V2.Dog\ntypealias Person = V2.Person\nenum V2 {\n    class Animal: CoreStoreObject {\n        // ...\n    }\n    class Dog: Animal {\n        // ...\n    }\n    class Person: CoreStoreObject {\n        // ...\n    }\n}\nenum V1 {\n    class Animal: CoreStoreObject {\n        // ...\n    }\n    class Dog: Animal {\n        // ...\n    }\n    class Person: CoreStoreObject {\n        // ...\n    }\n}\n\nCoreStoreDefaults.dataStack = DataStack(\n    CoreStoreSchema(\n        modelVersion: \"V1\",\n        entities: [\n            Entity\u003cV1.Animal\u003e(\"Animal\", isAbstract: true),\n            Entity\u003cV1.Dog\u003e(\"Dog\"),\n            Entity\u003cV1.Person\u003e(\"Person\")\n        ]\n    ),\n    CoreStoreSchema(\n        modelVersion: \"V2\",\n        entities: [\n            Entity\u003cV2.Animal\u003e(\"Animal\", isAbstract: true),\n            Entity\u003cV2.Dog\u003e(\"Dog\"),\n            Entity\u003cV2.Person\u003e(\"Person\")\n        ]\n    ),\n    migrationChain: [\"V1\", \"V2\"]\n)\n```\n\n\n### Starting migrations\nWe have seen `addStorageAndWait(...)` used to initialize our persistent store. As the method name's *~AndWait* suffix suggests though, this method blocks so it should not do long tasks such as data migrations. In fact CoreStore will only attempt a synchronous **lightweight** migration if you explicitly provide the `.allowSynchronousLightweightMigration` option:\n```swift\ntry dataStack.addStorageAndWait(\n    SQLiteStore(\n        fileURL: sqliteFileURL,\n        localStorageOptions: .allowSynchronousLightweightMigration\n    )\n}\n```\nif you do so, any model mismatch will be thrown as an error. \n\nIn general though, if migrations are expected the asynchronous variant `addStorage(_:completion:)` method is recommended instead:\n```swift\nlet migrationProgress: Progress? = try dataStack.addStorage(\n    SQLiteStore(\n        fileName: \"MyStore.sqlite\",\n        configuration: \"Config2\"\n    ),\n    completion: { (result) -\u003e Void in\n        switch result {\n        case .success(let storage):\n            print(\"Successfully added sqlite store: \\(storage)\")\n        case .failure(let error):\n            print(\"Failed adding sqlite store with error: \\(error)\")\n        }\n    }\n)\n```\nThe `completion` block reports a `SetupResult` that indicates success or failure.\n\n(A reactive-programming variant of this method is explained further in the section on [`DataStack` Combine publishers](#datastackreactive))\n\nNotice that this method also returns an optional `Progress`. If `nil`, no migrations are needed, thus progress reporting is unnecessary as well. If not `nil`, you can use this to track migration progress by using standard KVO on the `\"fractionCompleted\"` key, or by using a closure-based utility exposed in *Progress+Convenience.swift*:\n```swift\nmigrationProgress?.setProgressHandler { [weak self] (progress) -\u003e Void in\n    self?.progressView?.setProgress(Float(progress.fractionCompleted), animated: true)\n    self?.percentLabel?.text = progress.localizedDescription // \"50% completed\"\n    self?.stepLabel?.text = progress.localizedAdditionalDescription // \"0 of 2\"\n}\n```\nThis closure is executed on the main thread so UIKit and AppKit calls can be done safely.\n\n\n### Progressive migrations\nBy default, CoreStore uses Core Data's default automatic migration mechanism. In other words, CoreStore will try to migrate the existing persistent store until it matches the `SchemaHistory`'s `currentModelVersion`. If no mapping model path is found from the store's version to the data model's version, CoreStore gives up and reports an error.\n\nThe `DataStack` lets you specify hints on how to break a migration into several sub-migrations using a `MigrationChain`. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants:\n```swift\nlet dataStack = DataStack(migrationChain: \n    [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\"])\n```\nThe most common usage is to pass in the model version (*.xcdatamodeld* version names for `NSManagedObject`s, or the `modelName` for `CoreStoreSchema`s) in increasing order as above.\n\nFor more complex, non-linear migration paths, you can also pass in a version tree that maps the key-values to the source-destination versions:\n```swift\nlet dataStack = DataStack(migrationChain: [\n    \"MyAppModel\": \"MyAppModelV3\",\n    \"MyAppModelV2\": \"MyAppModelV4\",\n    \"MyAppModelV3\": \"MyAppModelV4\"\n])\n```\nThis allows for different migration paths depending on the starting version. The example above resolves to the following paths:\n- MyAppModel-MyAppModelV3-MyAppModelV4\n- MyAppModelV2-MyAppModelV4\n- MyAppModelV3-MyAppModelV4\n\nInitializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to disable progressive migrations and revert to the default migration behavior (i.e. use the *.xcdatamodeld*'s current version as the final version):\n```swift\nlet dataStack = DataStack(migrationChain: nil)\n```\n\nThe `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met:\n- a version appears twice in an array\n- a version appears twice as a key in a dictionary literal\n- a loop is found in any of the paths\n\n\u003e ⚠️**Important: If a `MigrationChain` is specified, the *.xcdatamodeld*'s \"Current Version\" will be bypassed** and the `MigrationChain`'s leafmost version will be the `DataStack`'s base model version.\n\n\n### Forecasting migrations\n\nSometimes migrations are huge and you may want prior information so your app could display a loading screen, or to display a confirmation dialog to the user. For this, CoreStore provides a `requiredMigrationsForStorage(_:)` method you can use to inspect a persistent store before you actually call `addStorageAndWait(_:)` or `addStorage(_:completion:)`:\n```swift\ndo {\n    let storage = SQLiteStorage(fileName: \"MyStore.sqlite\")\n    let migrationTypes: [MigrationType] = try dataStack.requiredMigrationsForStorage(storage)\n    if migrationTypes.count \u003e 1\n        || (migrationTypes.filter { $0.isHeavyweightMigration }.count) \u003e 0 {\n        // ... will migrate more than once. Show special waiting screen\n    }\n    else if migrationTypes.count \u003e 0 {\n        // ... will migrate just once. Show simple activity indicator\n    }\n    else {\n        // ... Do nothing\n    }\n    dataStack.addStorage(storage, completion: { /* ... */ })\n}\ncatch {\n    // ... either inspection of the store failed, or if no mapping model was found/inferred\n}\n```\n`requiredMigrationsForStorage(_:)` returns an array of `MigrationType`s, where each item in the array may be either of the following values:\n```swift\ncase lightweight(sourceVersion: String, destinationVersion: String)\ncase heavyweight(sourceVersion: String, destinationVersion: String)\n```\nEach `MigrationType` indicates the migration type for each step in the `MigrationChain`. Use these information as fit for your app.\n\n\n### Custom migrations\n\nCoreStore offers several ways to declare migration mappings:\n\n- `CustomSchemaMappingProvider`: A mapping provider that infers mapping initially, but also accepts custom mappings for specified entities. This was added to support custom migrations with `CoreStoreObject`s as well, but may also be used with `NSManagedObject`s.\n- `XcodeSchemaMappingProvider`: A mapping provider which loads entity mappings from *.xcmappingmodel* files in a specified `Bundle`.\n- `InferredSchemaMappingProvider`: The default mapping provider which tries to infer model migration between two `DynamicSchema` versions either by searching all *.xcmappingmodel* files from `Bundle.allBundles`, or by relying on lightweight migration if possible.\n\nThese mapping providers conform to `SchemaMappingProvider` and can be passed to `SQLiteStore`'s initializer:\n```swift\nlet dataStack = DataStack(migrationChain: [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\"])\n_ = try dataStack.addStorage(\n    SQLiteStore(\n        fileName: \"MyStore.sqlite\",\n        migrationMappingProviders: [\n            XcodeSchemaMappingProvider(from: \"V1\", to: \"V2\", mappingModelBundle: Bundle.main),\n            CustomSchemaMappingProvider(from: \"V2\", to: \"V3\", entityMappings: [.deleteEntity(\"Person\") ])\n        ]\n    ),\n    completion: { (result) -\u003e Void in\n        // ...\n    }\n)\n```\n\nFor version migrations present in the `DataStack`'s `MigrationChain` but not handled by any of the `SQLiteStore`'s `migrationMappingProviders` array, CoreStore will automatically try to use `InferredSchemaMappingProvider` as fallback. Finally if the `InferredSchemaMappingProvider` could not resolve any mapping, the migration will fail and the `DataStack.addStorage(...)` method will report the failure.\n\nFor `CustomSchemaMappingProvider`, more granular updates are supported through the dynamic objects `UnsafeSourceObject` and `UnsafeDestinationObject`. The example below allows the migration to conditionally ignore some objects:\n```swift\nlet person_v2_to_v3_mapping = CustomSchemaMappingProvider(\n    from: \"V2\",\n    to: \"V3\",\n    entityMappings: [\n        .transformEntity(\n            sourceEntity: \"Person\",\n            destinationEntity: \"Person\",\n            transformer: { (sourceObject: UnsafeSourceObject, createDestinationObject: () -\u003e UnsafeDestinationObject) in\n                \n                if (sourceObject[\"isVeryOldAccount\"] as! Bool?) == true {\n                    return // this account is too old, don't migrate \n                }\n                // migrate the rest\n                let destinationObject = createDestinationObject()\n                destinationObject.enumerateAttributes { (attribute, sourceAttribute) in\n                \n                if let sourceAttribute = sourceAttribute {\n                    destinationObject[attribute] = sourceObject[sourceAttribute]\n                }\n            }\n        ) \n    ]\n)\nSQLiteStore(\n    fileName: \"MyStore.sqlite\",\n    migrationMappingProviders: [person_v2_to_v3_mapping]\n)\n```\nThe `UnsafeSourceObject` is a read-only proxy for an object existing in the source model version. The `UnsafeDestinationObject` is a read-write object that is inserted (optionally) to the destination model version. Both classes' properties are accessed through key-value-coding.\n\n\n## Saving and processing transactions\nTo ensure deterministic state for objects in the read-only `NSManagedObjectContext`, CoreStore does not expose API's for updating and saving directly from the main context (or any other context for that matter.) Instead, you spawn *transactions* from `DataStack` instances:\n```swift\nlet dataStack = self.dataStack\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        // make changes\n    },\n    completion: { (result) -\u003e Void in\n        // ...\n    }\n)\n```\nTransaction closures automatically save changes once the closures completes. To cancel and rollback a transaction, throw a `CoreStoreError.userCancelled` from inside the closure by calling `try transaction.cancel()`:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        // ...\n        if shouldCancel {\n            try transaction.cancel()\n        }\n        // ...\n    },\n    completion: { (result) -\u003e Void in\n        if case .failure(.userCancelled) = result {\n            // ... cancelled\n        }\n    }\n)\n```\n\u003e ⚠️**Important:** Never use `try?` or `try!` on a `transaction.cancel()` call. Always use `try`. Using `try?` will swallow the cancellation and the transaction will proceed to save as normal. Using `try!` will crash the app as `transaction.cancel()` will *always* throw an error.\n\nThe examples above use `perform(asynchronous:...)`, but there are actually 3 types of transactions at your disposal: *asynchronous*, *synchronous*, and *unsafe*.\n\n### Transaction types\n\n#### Asynchronous transactions\nare spawned from `perform(asynchronous:...)`. This method returns immediately and executes its closure from a background serial queue. The return value for the closure is declared as a generic type, so any value returned from the closure can be passed to the completion result:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Bool in\n        // make changes\n        return transaction.hasChanges\n    },\n    completion: { (result) -\u003e Void in\n        switch result {\n        case .success(let hasChanges): print(\"success! Has changes? \\(hasChanges)\")\n        case .failure(let error): print(error)\n        }\n    }\n)\n```\nThe success and failure can also be declared as separate handlers:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Int in\n        // make changes\n        return transaction.delete(objects)\n    },\n    success: { (numberOfDeletedObjects: Int) -\u003e Void in\n        print(\"success! Deleted \\(numberOfDeletedObjects) objects\")\n    },\n    failure: { (error) -\u003e Void in\n        print(error)\n    }\n)\n```\n\n\u003e ⚠️Be careful when returning `NSManagedObject`s or `CoreStoreObject`s from the transaction closure. Those instances are for the transaction's use only. See [Passing objects safely](#passing-objects-safely).\n\nTransactions created from `perform(asynchronous:...)` are instances of `AsynchronousDataTransaction`.\n\n#### Synchronous transactions\nare created from `perform(synchronous:...)`. While the syntax is similar to its asynchronous counterpart, `perform(synchronous:...)` waits for its transaction block to complete before returning:\n```swift\nlet hasChanges = dataStack.perform(\n    synchronous: { (transaction) -\u003e Bool in\n        // make changes\n        return transaction.hasChanges\n    }\n)\n```\n`transaction` above is a `SynchronousDataTransaction` instance.\n\nSince `perform(synchronous:...)` technically blocks two queues (the caller's queue and the transaction's background queue), it is considered less safe as it's more prone to deadlock. Take special care that the closure does not block on any other external queues.\n\nBy default, `perform(synchronous:...)` will wait for observers such as `ListMonitor`s to be notified before the method returns. This may cause deadlocks, especially if you are calling this from the main thread. To reduce this risk, you may try to set the `waitForAllObservers:` parameter to `false`. Doing so tells the `SynchronousDataTransaction` to block only until it completes saving. It will not wait for other context's to receive those changes. This reduces deadlock risk but may have surprising side-effects:\n```swift\ndataStack.perform(\n    synchronous: { (transaction) in\n        let person = transaction.create(Into\u003cPerson\u003e())\n        person.name = \"John\"\n    },\n    waitForAllObservers: false\n)\nlet newPerson = dataStack.fetchOne(From\u003cPerson\u003e.where(\\.name == \"John\"))\n// newPerson may be nil!\n// The DataStack may have not yet received the update notification.\n```\nDue to this complicated nature of synchronous transactions, if your app has very heavy transaction throughput it is highly recommended to use [asynchronous transactions](#asynchronous-transactions) instead.\n\n#### Unsafe transactions\nare special in that they do not enclose updates within a closure:\n```swift\nlet transaction = dataStack.beginUnsafe()\n// make changes\ndownloadJSONWithCompletion({ (json) -\u003e Void in\n\n    // make other changes\n    transaction.commit()\n})\ndownloadAnotherJSONWithCompletion({ (json) -\u003e Void in\n\n    // make some other changes\n    transaction.commit()\n})\n```\nThis allows for non-contiguous updates. Do note that this flexibility comes with a price: you are now responsible for managing concurrency for the transaction. As uncle Ben said, \"with great power comes great race conditions.\"\n\nAs the above example also shows, with unsafe transactions `commit()` can be called multiple times.\n\n\nYou've seen how to create transactions, but we have yet to see how to make *creates*, *updates*, and *deletes*. The 3 types of transactions above are all subclasses of `BaseDataTransaction`, which implements the methods shown below.\n\n### Creating objects\n\nThe `create(...)` method accepts an `Into` clause which specifies the entity for the object you want to create:\n```swift\nlet person = transaction.create(Into\u003cMyPersonEntity\u003e())\n```\nWhile the syntax is straightforward, CoreStore does not just naively insert a new object. This single line does the following:\n- Checks that the entity type exists in any of the transaction's parent persistent store\n- If the entity belongs to only one persistent store, a new object is inserted into that store and returned from `create(...)`\n- If the entity does not belong to any store, an assertion failure will be raised. **This is a programmer error and should never occur in production code.**\n- If the entity belongs to multiple stores, an assertion failure will be raised. **This is also a programmer error and should never occur in production code.** Normally, with Core Data you can insert an object in this state but saving the `NSManagedObjectContext` will always fail. CoreStore checks this for you at creation time when it makes sense (not during save).\n\nIf the entity exists in multiple configurations, you need to provide the configuration name for the destination persistent store:\n```swift\nlet person = transaction.create(Into\u003cMyPersonEntity\u003e(\"Config1\"))\n```\nor if the persistent store is the auto-generated \"Default\" configuration, specify `nil`:\n```swift\nlet person = transaction.create(Into\u003cMyPersonEntity\u003e(nil))\n```\nNote that if you do explicitly specify the configuration name, CoreStore will only try to insert the created object to that particular store and will fail if that store is not found; it will not fall back to any other configuration that the entity belongs to. \n\n### Updating objects\n\nAfter creating an object from the transaction, you can simply update its properties as normal:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let person = transaction.create(Into\u003cMyPersonEntity\u003e())\n        person.name = \"John Smith\"\n        person.age = 30\n    },\n    completion: { _ in }\n)\n```\nTo update an existing object, fetch the object's instance from the transaction:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let person = try transaction.fetchOne(\n            From\u003cMyPersonEntity\u003e()\n                .where(\\.name == \"Jane Smith\")\n        )\n        person.age = person.age + 1\n    },\n    completion: { _ in }\n)\n```\n*(For more about fetching, see [Fetching and querying](#fetching-and-querying))*\n\n**Do not update an instance that was not created/fetched from the transaction.** If you have a reference to the object already, use the transaction's `edit(...)` method to get an editable proxy instance for that object:\n```swift\nlet jane: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        // WRONG: jane.age = jane.age + 1\n        // RIGHT:\n        let jane = transaction.edit(jane)! // using the same variable name protects us from misusing the non-transaction instance\n        jane.age = jane.age + 1\n    },\n    completion: { _ in }\n)\n```\nThis is also true when updating an object's relationships. Make sure that the object assigned to the relationship is also created/fetched from the transaction:\n```swift\nlet jane: MyPersonEntity = // ...\nlet john: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        // WRONG: jane.friends = [john]\n        // RIGHT:\n        let jane = transaction.edit(jane)!\n        let john = transaction.edit(john)!\n        jane.friends = NSSet(array: [john])\n    },\n    completion: { _ in }\n)\n```\n\n### Deleting objects\n\nDeleting an object is simpler because you can tell a transaction to delete an object directly without fetching an editable proxy (CoreStore does that for you):\n```swift\nlet john: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        transaction.delete(john)\n    },\n    completion: { _ in }\n)\n```\nor several objects at once:\n```swift\nlet john: MyPersonEntity = // ...\nlet jane: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        try transaction.delete(john, jane)\n        // try transaction.delete([john, jane]) is also allowed\n    },\n    completion: { _ in }\n)\n```\nIf you do not have references yet to the objects to be deleted, transactions have a `deleteAll(...)` method you can pass a query to:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        try transaction.deleteAll(\n            From\u003cMyPersonEntity\u003e()\n                .where(\\.age \u003e 30)\n        )\n    },\n    completion: { _ in }\n)\n```\n\n### Passing objects safely\n\nAlways remember that the `DataStack` and individual transactions manage different `NSManagedObjectContext`s so you cannot just use objects between them. That's why transactions have an `edit(...)` method:\n```swift\nlet jane: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let jane = transaction.edit(jane)!\n        jane.age = jane.age + 1\n    },\n    completion: { _ in }\n)\n```\nBut `CoreStore`, `DataStack` and `BaseDataTransaction` have a very flexible `fetchExisting(...)` method that you can pass instances back and forth with:\n```swift\nlet jane: MyPersonEntity = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e MyPersonEntity in\n        let jane = transaction.fetchExisting(jane)! // instance for transaction\n        jane.age = jane.age + 1\n        return jane\n    },\n    success: { (transactionJane) in\n        let jane = dataStack.fetchExisting(transactionJane)! // instance for DataStack\n        print(jane.age)\n    },\n    failure: { (error) in\n        // ...\n    }\n)\n```\n`fetchExisting(...)` also works with multiple `NSManagedObject`s, `CoreStoreObject`s, or with `NSManagedObjectID`s:\n```swift\nvar peopleIDs: [NSManagedObjectID] = // ...\n\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let jane = try transaction.fetchOne(\n            From\u003cMyPersonEntity\u003e()\n                .where(\\.name == \"Jane Smith\")\n        )\n        jane.friends = NSSet(array: transaction.fetchExisting(peopleIDs)!)\n        // ...\n    },\n    completion: { _ in }\n)\n```\n\n\n## Importing data\nSome times, if not most of the time, the data that we save to Core Data comes from external sources such as web servers or external files. If you have a JSON dictionary for example, you may be extracting values as such:\n```swift\nlet json: [String: Any] = // ...\nperson.name = json[\"name\"] as? NSString\nperson.age = json[\"age\"] as? NSNumber\n// ...\n```\nIf you have many attributes, you don't want to keep repeating this mapping everytime you want to import data. CoreStore lets you write the data mapping code just once, and all you have to do is call `importObject(...)` or `importUniqueObject(...)` through `BaseDataTransaction` subclasses:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let json: [String: Any] = // ...\n        try! transaction.importObject(\n            Into\u003cMyPersonEntity\u003e(),\n            source: json\n        )\n    },\n    completion: { _ in }\n)\n```\nTo support data import for an entity, implement either `ImportableObject` or `ImportableUniqueObject` on the `NSManagedObject` or `CoreStoreObject` subclass:\n- `ImportableObject`: Use this protocol if the object have no inherent uniqueness and new objects should always be added when calling `importObject(...)`.\n- `ImportableUniqueObject`: Use this protocol to specify a unique ID for an object that will be used to distinguish whether a new object should be created or if an existing object should be updated when calling `importUniqueObject(...)`.\n\nBoth protocols require implementers to specify an `ImportSource` which can be set to any type that the object can extract data from:\n```swift\ntypealias ImportSource = NSDictionary\n```\n```swift\ntypealias ImportSource = [String: Any]\n```\n```swift\ntypealias ImportSource = NSData\n```\nYou can even use external types from popular 3rd-party JSON libraries, or just simple tuples or primitives.\n\n#### `ImportableObject`\n`ImportableObject` is a very simple protocol:\n```swift\npublic protocol ImportableObject: AnyObject {\n    typealias ImportSource\n    static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -\u003e Bool\n    func didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws\n}\n```\nFirst, set `ImportSource` to the expected type of the data source:\n```swift\ntypealias ImportSource = [String: Any]\n```\nThis lets us call `importObject(_:source:)` with any `[String: Any]` type as the argument to `source`:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let json: [String: Any] = // ...\n        try! transaction.importObject(\n            Into\u003cMyPersonEntity\u003e(),\n            source: json\n        )\n        // ...\n    },\n    completion: { _ in }\n)\n```\nThe actual extraction and assignment of values should be implemented in the `didInsert(from:in:)` method of the `ImportableObject` protocol:\n```swift\nfunc didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws {\n    self.name = source[\"name\"] as? NSString\n    self.age = source[\"age\"] as? NSNumber\n    // ...\n}\n```\nTransactions also let you import multiple objects at once using the `importObjects(_:sourceArray:)` method:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let jsonArray: [[String: Any]] = // ...\n        try! transaction.importObjects(\n            Into\u003cMyPersonEntity\u003e(),\n            sourceArray: jsonArray // make sure this is of type Array\u003cMyPersonEntity.ImportSource\u003e\n        )\n        // ...\n    },\n    completion: { _ in }\n)\n```\nDoing so tells the transaction to iterate through the array of import sources and calls `shouldInsert(from:in:)` on the `ImportableObject` to determine which instances should be created. You can do validations and return `false` from `shouldInsert(from:in:)` if you want to skip importing from a source and continue on with the other sources in the array.\n\nIf on the other hand, your validation in one of the sources failed in such a manner that all other sources should also be rolled back and cancelled, you can `throw` from within `didInsert(from:in:)`:\n```swift\nfunc didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws {\n    self.name = source[\"name\"] as? NSString\n    self.age = source[\"age\"] as? NSNumber\n    // ...\n    if self.name == nil {\n        throw Errors.InvalidNameError\n    }\n}\n```\nDoing so can let you abandon an invalid transaction immediately:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let jsonArray: [[String: Any]] = // ...\n\n        try transaction.importObjects(\n            Into\u003cMyPersonEntity\u003e(),\n            sourceArray: jsonArray\n        )\n    },\n    success: {\n        // ...\n    },\n    failure: { (error) in\n        switch error {\n        case Errors.InvalidNameError: print(\"Invalid name\")\n        // ...\n        }\n    }\n)\n```\n\n#### `ImportableUniqueObject`\nTypically, we don't just keep creating objects every time we import data. Usually we also need to update already existing objects. Implementing the `ImportableUniqueObject` protocol lets you specify a \"unique ID\" that transactions can use to search existing objects before creating new ones:\n```swift\npublic protocol ImportableUniqueObject: ImportableObject {\n    typealias ImportSource\n    typealias UniqueIDType: ImportableAttributeType\n\n    static var uniqueIDKeyPath: String { get }\n    var uniqueIDValue: UniqueIDType { get set }\n\n    static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -\u003e Bool\n    static func shouldUpdate(from source: ImportSource, in transaction: BaseDataTransaction) -\u003e Bool\n    static func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -\u003e UniqueIDType?\n    func didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws\n    func update(from source: ImportSource, in transaction: BaseDataTransaction) throws\n}\n```\nNotice that it has the same insert methods as `ImportableObject`, with additional methods for updates and for specifying the unique ID:\n```swift\nclass var uniqueIDKeyPath: String {\n    return #keyPath(MyPersonEntity.personID) \n}\nvar uniqueIDValue: Int { \n    get { return self.personID }\n    set { self.personID = newValue }\n}\nclass func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -\u003e Int? {\n    return source[\"id\"] as? Int\n}\n```\nFor `ImportableUniqueObject`, the extraction and assignment of values should be implemented from the `update(from:in:)` method. The `didInsert(from:in:)` by default calls `update(from:in:)`, but you can separate the implementation for inserts and updates if needed.\n\nYou can then create/update an object by calling a transaction's `importUniqueObject(...)` method:\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let json: [String: Any] = // ...\n        try! transaction.importUniqueObject(\n            Into\u003cMyPersonEntity\u003e(),\n            source: json\n        )\n        // ...\n    },\n    completion: { _ in }\n)\n```\nor multiple objects at once with the `importUniqueObjects(...)` method:\n\n```swift\ndataStack.perform(\n    asynchronous: { (transaction) -\u003e Void in\n        let jsonArray: [[String: AnyObject]] = // ...\n        try! transaction.importUniqueObjects(\n            Into\u003cMyPersonEntity\u003e(),\n            sourceArray: jsonArray\n        )\n        // ...\n    },\n    completion: { _ in }\n)\n```\nAs with `ImportableObject`, you can control whether to skip importing an object by implementing \n`shouldInsert(from:in:)` and `shouldUpdate(from:in:)`, or to cancel all objects by `throw`ing an error from the `uniqueID(from:in:)`, `didInsert(from:in:)` or `update(from:in:)` methods.\n\n\n## Fetching and Querying\nBefore we dive in, be aware that CoreStore distinguishes between *fetching* and *querying*:\n- A *fetch* executes searches from a specific *transaction* or *data stack*. This means fetches can include pending objects (i.e. before a transaction calls on `commit()`.) Use fetches when:\n    - results need to be `NSManagedObject` or `CoreStoreObject` instances\n    - unsaved objects should be included in the search (though fetches can be configured to exclude unsaved ones)\n- A *query* pulls data straight from the persistent store. This means faster searches when computing aggregates such as *count*, *min*, *max*, etc. Use queries when:\n    - you need to compute aggregate functions (see below for a list of supported functions)\n    - results can be raw values like `NSString`s, `NSNumber`s, `Int`s, `NSDate`s, an `NSDictionary` of key-values, or any type that conform to `QueryableAttributeType`. (See *QueryableAttributeType.swift* for a list of built-in types)\n    - only values for specified attribute keys need to be included in the results\n    - unsaved objects should be ignored\n\n#### `From` clause\nThe search conditions for fetches and queries are specified using *clauses*. All fetches and queries require a `From` clause that indicates the target entity type:\n```swift\nlet people = try dataStack.fetchAll(From\u003cMyPersonEntity\u003e())\n```\n`people` in the example above will be of type `[MyPersonEntity]`. The `From\u003cMyPersonEntity\u003e()` clause indicates a fetch to all persistent stores that `MyPersonEntity` belong to.\n\nIf the entity exists in multiple configurations and you need to only search from a particular configuration, indicate in the `From` clause the configuration name for the destination persistent store:\n```swift\nlet people = try dataStack.fetchAll(From\u003cMyPersonEntity\u003e(\"Config1\")) // ignore objects in persistent stores other than the \"Config1\" configuration\n```\nor if the persistent store is the auto-generated \"Default\" configuration, specify `nil`:\n```swift\nlet person = try dataStack.fetchAll(From\u003cMyPersonEntity\u003e(nil))\n```\nNow we know how to use a `From` clause, let's move on to fetching and querying.\n\n### Fetching\n\nThere are currently 5 fetch methods you can call from `CoreStore`, from a `DataStack` instance, or from a `BaseDataTransaction` instance. All of the methods below accept the same parameters: a required `From` clause, and an optional series of `Where`, `OrderBy`, and/or `Tweak` clauses.\n\n- `fetchAll(...)` - returns an array of all objects that match the criteria.\n- `fetchOne(...)` - returns the first object that match the criteria.\n- `fetchCount(...)` - returns the number of objects that match the criteria.\n- `fetchObjectIDs(...)` - returns an array of `NSManagedObjectID`s for all objects that match the criteria.\n- `fetchObjectID(...)` - returns the `NSManagedObjectID`s for the first objects that match the criteria.\n\nEach method's purpose is straightforward, but we need to understand how to set the clauses for the fetch.\n\n#### `Where` clause\n\nThe `Where` clause is CoreStore's `NSPredicate` wrapper. It specifies the search filter to use when fetching (or querying). It implements all initializers that `NSPredicate` does (except for `-predicateWithBlock:`, which Core Data does not support):\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    Where\u003cMyPersonEntity\u003e(\"%K \u003e %d\", \"age\", 30) // string format initializer\n)\npeople = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    Where\u003cMyPersonEntity\u003e(true) // boolean initializer\n)\n```\nIf you do have an existing `NSPredicate` instance already, you can pass that to `Where` as well:\n```swift\nlet predicate = NSPredicate(...)\nvar people = dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    Where\u003cMyPersonEntity\u003e(predicate) // predicate initializer\n)\n```\n `Where` clauses are generic types. To avoid verbose repetition of the generic object type, fetch methods support **Fetch Chain builders**. We can also use Swift's Smart KeyPaths as the `Where` clause expression:\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e()\n        .where(\\.age \u003e 30) // Type-safe!\n)\n```\n`Where` clauses also implement the `\u0026\u0026`, `||`, and `!` logic operators, so you can provide logical conditions without writing too much `AND`, `OR`, and `NOT` strings:\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e()\n        .where(\\.age \u003e 30 \u0026\u0026 \\.gender == \"M\")\n)\n```\nIf you do not provide a `Where` clause, all objects that belong to the specified `From` will be returned.\n\n#### `OrderBy` clause\n\nThe `OrderBy` clause is CoreStore's `NSSortDescriptor` wrapper. Use it to specify attribute keys in which to sort the fetch (or query) results with.\n```swift\nvar mostValuablePeople = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    OrderBy\u003cMyPersonEntity\u003e(.descending(\"rating\"), .ascending(\"surname\"))\n)\n```\nAs seen above, `OrderBy` accepts a list of `SortKey` enumeration values, which can be either `.ascending` or `.descending`.\nAs with `Where` clauses, `OrderBy` clauses are also generic types. To avoid verbose repetition of the generic object type, fetch methods support **Fetch Chain builders**. We can also use Swift's Smart KeyPaths as the `OrderBy` clause expression:\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e()\n        .orderBy(.descending(\\.rating), .ascending(\\.surname)) // Type-safe!\n)\n```\n\nYou can use the `+` and `+=` operator to append `OrderBy`s together. This is useful when sorting conditionally:\n```swift\nvar orderBy = OrderBy\u003cMyPersonEntity\u003e(.descending(\\.rating))\nif sortFromYoungest {\n    orderBy += OrderBy(.ascending(\\.age))\n}\nvar mostValuablePeople = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    orderBy\n)\n```\n\n#### `Tweak` clause\n\nThe `Tweak` clause lets you, uh, *tweak* the fetch (or query). `Tweak` exposes the `NSFetchRequest` in a closure where you can make changes to its properties:\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n    Where\u003cMyPersonEntity\u003e(\"age \u003e %d\", 30),\n    OrderBy\u003cMyPersonEntity\u003e(.ascending(\"surname\")),\n    Tweak { (fetchRequest) -\u003e Void in\n        fetchRequest.includesPendingChanges = false\n        fetchRequest.returnsObjectsAsFaults = false\n        fetchRequest.includesSubentities = false\n    }\n)\n```\n`Tweak` also supports **Fetch Chain builders**:\n```swift\nvar people = try dataStack.fetchAll(\n    From\u003cMyPersonEntity\u003e(),\n        .where(\\.age \u003e 30)\n        .orderBy(.ascending(\\.surname))\n        .tweak {\n            $0.includesPendingChanges = false\n            $0.returnsObjectsAsFaults = false\n            $0.includesSubentities = false\n        }\n)\n```\nThe clauses are evaluated the order they appear in the fetch/query, so you typically need to set `Tweak` as the last clause.\n`Tweak`'s closure is executed only just before the fetch occurs, so make sure that any values captured by the closure is not prone to race conditions.\n\nWhile `Tweak` lets you micro-configure the `NSFetchRequest`, note that CoreStore already preconfigured that `NSFetchRequest` to suitable defaults. Only use `Tweak` when you know what you are doing!\n\n### Querying\n\nOne of the functionalities overlooked by other Core Data wrapper libraries is raw properties fetching. If you are familiar with `NSDictionaryResultType` and `-[NSFetchedRequest propertiesToFetch]`, you probably know how painful it is to setup a query for raw values and aggregate values. CoreStore makes this easy by exposing the 2 methods below:\n\n- `queryValue(...)` - returns a single raw value for an attribute or for an aggregate value. If there are multiple results, `queryValue(...)` only returns the first item.\n- `queryAttributes(...)` - returns an array of dictionaries containing attribute keys with their corresponding values.\n\nBoth methods above accept the same parameters: a required `From` clause, a required `Select\u003cT\u003e` clause, and an optional series of `Where`, `OrderBy`, `GroupBy`, and/or `Tweak` clauses.\n\nSetting up the `From`, `Where`, `OrderBy`, and `Tweak` clauses is similar to how you would when fetching. For querying, you also need to know how to use the `Select\u003cT\u003e` and `GroupBy` clauses.\n\n#### `Select\u003cT\u003e` clause\n\nThe `Select\u003cT\u003e` clause specifies the target attribute/aggregate key, as well as the expected return type: \n```swift\nlet johnsAge = try dataStack.queryValue(\n    From\u003cMyPersonEntity\u003e(),\n    Select\u003cInt\u003e(\"age\"),\n    Where\u003cMyPersonEntity\u003e(\"name == %@\", \"John Smith\")\n)\n```\nThe example above queries the \"age\" property for the first object that matches the `Where` condition. `johnsAge` will be bound to type `Int?`, as indicated by the `Select\u003cInt\u003e` generic type. For `queryValue(...)`, types that conform to `QueryableAttributeType` are allowed as the return type (and therefore as the generic type for `Select\u003cT\u003e`).\n\nFor `queryAttributes(...)`, only `NSDictionary` is valid for `Select`, thus you are allowed to omit the generic type:\n```swift\nlet allAges = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e(),\n    Select(\"age\")\n)\n```\nquery methods also support **Query Chain builders**. We can also use Swift's Smart KeyPaths to use in the expressions:\n```swift\nlet johnsAge = try dataStack.queryValue(\n    From\u003cMyPersonEntity\u003e()\n        .select(\\.age) // binds the result to Int\n        .where(\\.name == \"John Smith\")\n)\n```\n\nIf you only need a value for a particular attribute, you can just specify the key name (like we did with `Select\u003cInt\u003e(\"age\")`), but several aggregate functions can also be used as parameter to `Select`:\n- `.average(...)`\n- `.count(...)`\n- `.maximum(...)`\n- `.minimum(...)`\n- `.sum(...)`\n\n```swift\nlet oldestAge = try dataStack.queryValue(\n    From\u003cMyPersonEntity\u003e(),\n    Select\u003cInt\u003e(.maximum(\"age\"))\n)\n```\n\nFor `queryAttributes(...)` which returns an array of dictionaries, you can specify multiple attributes/aggregates to `Select`:\n```swift\nlet personJSON = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e(),\n    Select(\"name\", \"age\")\n)\n```\n`personJSON` will then have the value:\n```swift\n[\n    [\n        \"name\": \"John Smith\",\n        \"age\": 30\n    ],\n    [\n        \"name\": \"Jane Doe\",\n        \"age\": 22\n    ]\n]\n```\nYou can also include an aggregate as well:\n```swift\nlet personJSON = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e(),\n    Select(\"name\", .count(\"friends\"))\n)\n```\nwhich returns:\n```swift\n[\n    [\n        \"name\": \"John Smith\",\n        \"count(friends)\": 42\n    ],\n    [\n        \"name\": \"Jane Doe\",\n        \"count(friends)\": 231\n    ]\n]\n```\nThe `\"count(friends)\"` key name was automatically used by CoreStore, but you can specify your own key alias if you need:\n```swift\nlet personJSON = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e(),\n    Select(\"name\", .count(\"friends\", as: \"friendsCount\"))\n)\n```\nwhich now returns:\n```swift\n[\n    [\n        \"name\": \"John Smith\",\n        \"friendsCount\": 42\n    ],\n    [\n        \"name\": \"Jane Doe\",\n        \"friendsCount\": 231\n    ]\n]\n```\n\n#### `GroupBy` clause\n\nThe `GroupBy` clause lets you group results by a specified attribute/aggregate. This is useful only for `queryAttributes(...)` since `queryValue(...)` just returns the first value.\n```swift\nlet personJSON = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e(),\n    Select(\"age\", .count(\"age\", as: \"count\")),\n    GroupBy(\"age\")\n)\n```\n`GroupBy` clauses are also generic types and support **Query Chain builders**. We can also use Swift's Smart KeyPaths to use in the expressions:\n```swift\nlet personJSON = try dataStack.queryAttributes(\n    From\u003cMyPersonEntity\u003e()\n        .select(.attribute(\\.age), .count(\\.age, as: \"count\"))\n        .groupBy(\\.age)\n)\n```\nthis returns dictionaries that shows the count for each `\"age\"`:\n```swift\n[\n    [\n        \"age\": 42,\n        \"count\": 1\n    ],\n    [\n        \"age\": 22,\n        \"count\": 1\n    ]\n]\n```\n\n## Logging and error reporting\nOne unfortunate thing when using some third-party libraries is that they usually pollute the console with their own logging mechanisms. CoreStore provides its own default logging class, but you can plug-in your own favorite logger by implementing the `CoreStoreLogger` protocol.\n```swift\npublic protocol CoreStoreLogger {\n    func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)\n    func log(error error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)\n    func assert(@autoclosure condition: () -\u003e Bool, @autoclosure message: () -\u003e String, fileName: StaticString, lineNumber: Int, functionName: StaticString)\n    func abort(message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString)\n}\n```\nImplement this protocol with your custom class then pass the instance to `CoreStoreDefaults.logger`:\n```swift\nCoreStoreDefaults.logger = MyLogger()\n```\nDoing so channels all logging calls to your logger.\n\nNote that to keep the call stack information intact, all calls to these methods are **NOT** thread-managed. Therefore you have to make sure that your logger is thread-safe or you may otherwise have to dispatch your logging implementation to a serial queue.\n\nTake special care when implementing `CoreStoreLogger`'s `assert(...)` and `abort(...)` functions:\n- `assert(...)`: The behavior between `DEBUG` and release builds, or `-O` and `-Onone`, are all left to the implementers' responsibility. CoreStore calls `CoreStoreLogger.assert(...)` only for invalid but usually recoverable errors (for example, early validation failures that may cause an error thrown and handled somewhere else)\n- `abort(...)`: This method is *the* last-chance for your app to *synchronously* log a fatal error within CoreStore. The app will be terminated right after this function is called (CoreStore calls `fatalError()` internally)\n\nAll CoreStore types have very useful (and pretty formatted!) `print(...)` outputs. \nA couple of examples, `ListMonitor`:\n\n\u003cimg width=\"369\" alt=\"screen shot 2016-07-10 at 22 56 44\" src=\"https://cloud.githubusercontent.com/assets/3029684/16713994/ae06e702-46f1-11e6-83a8-dee48b480bab.png\" /\u003e\n\n`CoreStoreError.mappingModelNotFoundError`:\n\n\u003cimg width=\"506\" alt=\"MappingModelNotFoundError\" src=\"https://cloud.githubusercontent.com/assets/3029684/16713962/e021f548-46f0-11e6-8100-f9b5ea6b4a08.png\" /\u003e\n\nThese are all implemented with `CustomDebugStringConvertible.debugDescription`, so they work with lldb's `po` command as well.\n\n## Observing changes and notifications\n\nCoreStore provides type-safe wrappers for observing managed objects:\n\n| | 🆕[*ObjectPublisher*](#observe-a-single-objects-updates) | [*ObjectMonitor*](#observe-a-single-objects-per-property-updates) | 🆕[*ListPublisher*](#observe-a-diffable-list) | [*ListMonitor*](#observe-detailed-list-changes) |\n| --- | --- | --- | --- | --- |\n| *Number of objects* | 1 | 1 | N | N |\n| *Allows multiple observers* | ✅ | ✅ | ✅ | ✅ |\n| *Emits fine-grained changes* | ❌ | ✅ | ❌ | ✅ |\n| *Emits DiffableDataSource snapshots* | ✅ | ❌ | ✅ | ❌ |\n| *Delegate methods* | ❌ | ✅ | ❌ | ✅ |\n| *Closure callback* | ✅ | ❌ | ✅ | ❌ |\n| *SwiftUI support* | ✅ | ❌ | ✅ | ❌ |\n\n### Observe a single property\nTo get notifications for single property changes in an object, there are two methods depending on the object's base class.\n\n- For `NSManagedObject` subclasses: Use the standard KVO method:\n```swift\nlet observer = person.observe(\\.age, options: [.new]) { (person, change)\n    print(\"Happy \\(change.newValue)th birthday!\")\n}\n```\n\n- For `CoreStoreObject` subclasses: Call the `observe(...)` method directly on the property. You'll notice that the API itself is a bit similar to the KVO method:\n```swift\nlet observer = person.age.observe(options: [.new]) { (person, change)\n    print(\"Happy \\(change.newValue)th birthday!\")\n}\n```\n\nFor both methods, you will need to keep a reference to the returned `observer` for the duration of the observation.  \n\n### Observe a single object's updates\n\nObservers of an  `ObjectPublisher` can receive notifications if any of the object's property changes. You can  create an `ObjectPublisher` from the object directly:\n```swift\nlet objectPublisher: ObjectPublisher\u003cPerson\u003e = person.asPublisher(in: dataStack)\n```\nor by indexing a `ListPublisher`'s `ListSnapshot`:\n```swift\nlet listPublisher: ListPublisher\u003cPerson\u003e = // ...\n// ...\nlet objectPublisher = listPublisher.snapshot[indexPath]\n```\n(See [`ListPublisher` examples](#observe-a-diffable-list) below)\n\nTo receive notifications, call the  `ObjectPublisher`'s `addObserve(...)` method passing the owner of the callback closure:\n```swift\nobjectPublisher.addObserver(self) { [weak self] (objectPublisher) in\n    let snapshot: ObjectSnapshot\u003cPerson\u003e = objectPublisher.snapshot\n    // handle changes\n}\n```\nNote that the owner instance will not be retained. You may call `ObjectPublisher.removeObserver(...)` explicitly to stop receiving notifications, but the `ObjectPublisher` also discontinues sending events to deallocated observers.\n\nThe `ObjectSnapshot` returned from the `ObjectPublisher.snapshot` property returns a full-copy `struct` of all properties of the object. This is ideal for managing states as they are thread-safe and are not affected by further changes to the actual object.  `ObjectPublisher` automatically updates its `snapshot` value to the latest state of the object. \n\n(A reactive-programming variant of this method is explained in detail in the section on [`ObjectPublisher` Combine publishers](#objectpublisherreactive))\n\n\n### Observe a single object's per-property updates\n\nIf you need to track specifically which properties change in an object, implement the `ObjectObserver` protocol and specify the `EntityType`:\n```swift\nclass MyViewController: UIViewController, ObjectObserver {\n    func objectMonitor(monitor: ObjectMonitor\u003cMyPersonEntity\u003e, willUpdateObject object: MyPersonEntity) {\n        // ...\n    }\n    \n    func objectMonitor(monitor: ObjectMonitor\u003cMyPersonEntity\u003e, didUpdateObject object: MyPersonEntity, changedPersistentKeys: Set\u003cKeyPathString\u003e) {\n        // ...\n    }\n    \n    func objectMonitor(monitor: ObjectMonitor\u003cMyPersonEntity\u003e, didDeleteObject object: MyPersonEntity) {\n        // ...\n    }\n}\n```\nWe then need to keep an `ObjectMonitor` instance and register our `ObjectObserver` as an observer:\n```swift\nlet person: MyPersonEntity = // ...\nself.monitor = dataStack.monitorObject(person)\nself.monitor.addObserver(self)\n```\nThe controller will then notify our observer whenever the object's attributes change. You can add multiple `ObjectObserver`s to a single `ObjectMonitor` without any problem. This means you can just share around the `ObjectMonitor` instance to different screens without problem.\n\nYou can get `ObjectMonitor`'s object through its `object` property. If the object is deleted, the `object` property will become `nil` to prevent further access. \n\nWhile `ObjectMonitor` exposes `removeObserver(...)` as well, it only stores `weak` references of the observers and will safely unregister deallocated observers. \n\n### Observe a diffable list\n\nObservers of a  `ListPublisher` can receive notifications whenever its fetched result set changes. You can  create a `ListPublisher` by fetching from the `DataStack`:\n```swift\nlet listPublisher = dataStack.listPublisher(\n    From\u003cPerson\u003e()\n        .sectionBy(\\.age\") { \"Age \\($0)\" } // sections are optional\n        .where(\\.title == \"Engineer\")\n        .orderBy(.ascending(\\.lastName))\n)\n```\nTo receive notifications, call the  `ListPublisher`'s `addObserve(...)` method passing the owner of the callback closure:\n```swift\nlistPublisher.addObserver(self) { [weak self] (listPublisher) in\n    let snapshot: ListSnapshot\u003cPerson\u003e = listPublisher.snapshot\n    // handle changes\n}\n```\nNote that the owner instance will not be retained. You may call `ListPublisher.removeObserver(...)` explicitly to stop receiving notifications, but the `ListPublisher` also discontinues sending events to deallocated observers.\n\nThe `ListSnapshot` returned from the `ListPublisher.snapshot` property returns a full-copy `struct` of all sections and `NSManagedObject` items in the list. This is ideal for managing states as they are thread-safe and are not affected by further changes to the result set.  `ListPublisher` automatically updates its `snapshot` value to the latest state of the fetch. \n\n(A reactive-programming variant of this method is explained in detail in the section on [`ListPublisher` Combine publishers](#listpublisherreactive))\n\nUnlike  `ListMonitor`s (See [`ListMonitor` examples](#observe-detailed-list-changes) below), a `ListPublisher` does not track detailed inserts, deletes, and moves. In return, a `ListPublisher` is a lot more lightweight and are designed to work well with `DiffableDataSource.TableViewAdapter`s and `DiffableDataSource.CollectionViewAdapter`s:\n```swift\nself.dataSource = DiffableDataSource.CollectionViewAdapter\u003cPerson\u003e(\n    collectionView: self.collectionView,\n    dataStack: CoreStoreDefaults.dataStack,\n    cellProvider: { (collectionView, indexPath, person) in\n        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: \"PersonCell\") as! PersonCell\n        cell.setPerson(person)\n        return cell\n    }\n)\n\n// ...\n\nlistPublisher.addObserver(self) { [weak self] (listPublisher) in\n   self?.dataSource?.apply(\n       listPublisher.snapshot, animatingDifferences: true\n   )\n}\n```\n\n### Observe detailed list changes\nIf you need to track each object's inserts, deletes, moves, and updates, implement one of the `ListObserver` protocols and specify the `EntityType`:\n```swift\nclass MyViewController: UIViewController, ListObserver {\n    func listMonitorDidChange(monitor: ListMonitor\u003cMyPersonEntity\u003e) {\n        // ...\n    }\n    \n    func listMonitorDidRefetch(monitor: ListMonitor\u003cMyPersonEntity\u003e) {\n        // ...\n    }\n}\n```\nIncluding `ListObserver`, there are 3 observer protocols you can implement depending on how detailed you need to handle a change notification:\n- `ListObserver`: lets you handle these callback methods:\n```swift\n    func listMonitorWillChange(_ monitor: ListMonitor\u003cMyPersonEntity\u003e)\n    func listMonitorDidChange(_ monitor: ListMonitor\u003cMyPersonEntity\u003e)\n    func listMonitorWillRefetch(_ monitor: ListMonitor\u003cMyPersonEntity\u003e)\n    func listMonitorDidRefetch(_ monitor: ListMonitor\u003cMyPersonEntity\u003e)\n```\n`listMonitorDidChange(_:)` and `listMonitorDidRefetch(_:)` implementations are both required. `listMonitorDidChange(_:)` is called whenever the `ListMonitor`'s count, order, or filtered objects change. `listMonitorDidRefetch(_:)` is called when the `ListMonitor.refetch()` was executed or if the internal persistent store was changed. \n\n- `ListObjectObserver`: in addition to `ListObserver` methods, also lets you handle object inserts, updates, and deletes:\n```swift\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didInsertObject object: MyPersonEntity, toIndexPath indexPath: IndexPath)\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didDeleteObject object: MyPersonEntity, fromIndexPath indexPath: IndexPath)\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didUpdateObject object: MyPersonEntity, atIndexPath indexPath: IndexPath)\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didMoveObject object: MyPersonEntity, fromIndexPath: IndexPath, toIndexPath: IndexPath)\n```\n- `ListSectionObserver`: in addition to `ListObjectObserver` methods, also lets you handle section inserts and deletes:\n```swift\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)\n    func listMonitor(_ monitor: ListMonitor\u003cMyPersonEntity\u003e, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)\n```\n\nWe then need to create a `ListMonitor` instance and register our `ListObserver` as an observer:\n```swift\nself.monitor = dataStack.monitorList(\n    From\u003cMyPersonEntity\u003e()\n        .where(\\.age \u003e 30)\n        .orderBy(.ascending(\\.name))\n        .tweak { $0.fetchBatchSize = 20 }\n)\nself.monitor.addObserver(self)\n```\nSimilar to `ObjectMonitor`, a `ListMonitor` can also have multiple `ListObserver`s registered to a single `ListMonitor`.\n\nIf you have noticed, the `monitorList(...)` method accepts `Where`, `OrderBy`, and `Tweak` clauses exactly like a fetch. As the list maintained by `ListMonitor` needs to have a deterministic order, at least the `From` and `OrderBy` clauses are required.\n\nA `ListMonitor` created from `monitorList(...)` will maintain a single-section list. You can therefore access its contents with just an index:\n```swift\nlet firstPerson = self.monitor[0]\n```\n\nIf the list needs to be grouped into sections, create the `ListMonitor` instance with the `monitorSectionedList(...)` method and a `SectionBy` clause:\n```swift\nself.monitor = dataStack.monitorSectionedList(\n    From\u003cMyPersonEntity\u003e()\n        .sectionBy(\\.age)\n        .where(\\.gender == \"M\")\n        .orderBy(.ascending(\\.age), .ascending(\\.name))\n        .tweak { $0.fetchBatchSize = 20 }\n)\n```\nA list controller created this way will group the objects by the attribute key indicated by the `SectionBy` clause. One more thing to remember is that the `OrderBy` clause should sort the list in such a way that the `SectionBy` attribute would be sorted together (a requirement shared by `NSFetchedResultsController`.)\n\nThe `SectionBy` clause can also be passed a closure to transform the section name into a displayable string:\n```swift\nself.monitor = dataStack.monitorSectionedList(\n    From\u003cMyPersonEntity\u003e()\n        .sectionBy(\\.age) { (sectionName) -\u003e String? in\n            \"\\(sectionName) years old\"\n        }\n        .orderBy(.ascending(\\.age), .ascending(\\.name))\n)\n```\nThis is useful when implementing a `UITableViewDelegate`'s section header:\n```swift\nfunc tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -\u003e String? {\n    let sectionInfo = self.monitor.sectionInfoAtIndex(section)\n    return sectionInfo.name\n}\n```\n\nTo access the objects of a sectioned list, use an `IndexPath` or a tuple:\n```swift\nlet indexPath = IndexPath(row: 2, section: 1)\nlet person1 = self.monitor[indexPath]\nlet person2 = self.monitor[1, 2]\n// person1 and person2 are the same object\n```\n\n## Type-safe `CoreStoreObject`s\nStarting CoreStore 4.0, we can now create persisted objects without depending on *.xcdatamodeld* Core Data files. The new `CoreStoreObject` subclass replaces `NSManagedObject`, and specially-typed properties declared on these classes will be synthesized as Core Data attributes.\n```swift\nclass Animal: CoreStoreObject {\n    @Field.Stored(\"species\")\n    var species: String = \"\"\n}\n\nclass Dog: Animal {\n    @Field.Stored(\"nickname\")\n    var nickname: String?\n    \n    @Field.Relationship(\"master\")\n    var master: Person?\n}\n\nclass Person: CoreStoreObject {\n    @Field.Stored(\"name\")\n    var name: String = \"\"\n    \n    @Field.Relationship(\"pets\", inverse: \\Dog.$master)\n    var pets: Set\u003cDog\u003e\n}\n```\nThe property names to be saved to Core Data is specified as the `keyPath` argument. This lets us refactor our Swift code without affecting the underlying database. For example:\n```swift\nclass Person: CoreStoreObject {\n    @Field.Stored(\"name\")\n    private var internalName: String = \"\"\n    // note property name is independent of the storage key name\n}\n```\nHere we used the property name `internalName` and made it `private`, but the underlying key-path `\"name\"` was unchanged so our model will not trigger a data migration.\n\nTo tell the `DataStack` about these types, add all `CoreStoreObject`s' entities to a `CoreStoreSchema`:\n```swift\n\nCoreStoreDefaults.dataStack = DataStack(\n    CoreStoreSchema(\n        modelVersion: \"V1\",\n        entities: [\n            Entity\u003cAnimal\u003e(\"Animal\", isAbstract: true),\n            Entity\u003cDog\u003e(\"Dog\"),\n            Entity\u003cPerson\u003e(\"Person\")\n        ]\n    )\n)\nCoreStoreDefaults.dataStack.addStorage(/* ... */)\n```\nAnd that's all CoreStore needs to build the model; **we don't need *.xcdatamodeld* files anymore.**\n\nIn addition, `@Field` properties can be used to create type-safe key-path strings\n```swift\nlet keyPath = String(keyPath: \\Dog.$nickname)\n```\nas well as `Where` and `OrderBy` clauses\n```swift\nlet puppies = try dataStack.fetchAll(\n    From\u003cDog\u003e()\n        .where(\\.$age \u003c 5)\n        .orderBy(.ascending(\\.$age))\n)\n```\n\nAll CoreStore APIs that are usable with `NSManagedObject`s are also available for `CoreStoreObject`s. These include `ListMonitor`s, `ImportableObject`s, fetching, etc.\n\n### New `@Field` Property Wrapper syntax\n\n\u003e ⚠️**Important:** `@Field` properties are only supported for `CoreStoreObject` subclasses. If you are using `NSManagedObject`s, you need to keep using `@NSManaged` for your attributes.\n\nStarting CoreStore 7.1.0, `CoreStoreObject` properties may be converted to `@Field` Property Wrappers.\n\n\u003e ‼️ Please take note of the warnings below before converting or else the model's hash might change.\n\n**If conversion is too risky, the current `Value.Required`, `Value.Optional`, `Transformable.Required`, `Transformable.Optional`, `Relationship.ToOne`, `Relationship.ToManyOrdered`, and `Relationship.ToManyUnordered` will all be supported for while so you can opt to use them as is for now.**\n\n\u003e ‼️ This cannot be stressed enough, but please make sure to set your schema's [`VersionLock`](#versionlocks) before converting!\n\n#### `@Field.Stored`\n\nThe `@Field.Stored` property wrapper is used for persisted value types. This is the replacement for \"non-transient\" `Value.Required` and `Value.Optional` properties.\n\n\u003ctable\u003e\n\u003ctr\u003e\u003cth\u003eBefore\u003c/th\u003e\u003cth\u003e\u003cpre lang=swift\u003e@Field.Stored\u003c/pre\u003e\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Person: CoreStoreObject {\n    \u003cbr /\u003e\n    let title = Value.Required\u0026lt;String\u0026gt;(\"title\", initial: \"Mr.\")\n    let nickname = Value.Optional\u0026lt;String\u0026gt;(\"nickname\")\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Person: CoreStoreObject {\n    \u003cbr /\u003e\n    @Field.Stored(\"title\")\n    var title: String = \"Mr.\"\n    \u003cbr /\u003e\n    @Field.Stored(\"nickname\")\n    var nickname: String?\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n\u003e ⚠️ Only `Value.Required` and `Value.Optional` that are NOT transient values can be converted to `Field.Stored`. For transient/computed properties, refer to [`@Field.Virtual`](#fieldvirtual) properties in the next section.\n\u003e ⚠️ When converting, make sure that all parameters, including the default values, are exactly the same or else the model's hash might change.\n\n\n#### `@Field.Virtual`\n\nThe `@Field.Virtual` property wrapper is used for unsaved, computed value types. This is the replacement for \"transient\" `Value.Required` and `Value.Optional` properties.\n\n\u003ctable\u003e\n\u003ctr\u003e\u003cth\u003eBefore\u003c/th\u003e\u003cth\u003e\u003cpre lang=swift\u003e@Field.Virtual\u003c/pre\u003e\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Animal: CoreStoreObject {\n    \u003cbr /\u003e\n    let speciesPlural = Value.Required\u0026lt;String\u0026gt;(\n        \"speciesPlural\",\n        transient: true,\n        customGetter: Animal.getSpeciesPlural(_:)\n    )\n    \u003cbr /\u003e\n    let species = Value.Required\u0026lt;String\u0026gt;(\"species\", initial: \"\")\n    \u003cbr /\u003e\n    static func getSpeciesPlural(_ partialObject: PartialObject\u0026lt;Animal\u0026gt;) -\u003e String? {\n        let species = partialObject.value(for: { $0.species })\n        return species + \"s\"\n    }\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Animal: CoreStoreObject {\n    \u003cbr /\u003e\n    @Field.Virtual(\n        \"speciesPlural\",\n        customGetter: { (object, field) in\n            return object.$species.value + \"s\"\n        }\n    )\n    var speciesPlural: String\n    \u003cbr /\u003e\n    @Field.Stored(\"species\")\n    var species: String = \"\"\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n\u003e ⚠️ Only `Value.Required` and `Value.Optional` that ARE transient values can be converted to `Field.Virtual`. For non-transient properties, refer to [`@Field.Stored`](#fieldstored) properties in the previous section.\n\u003e ⚠️ When converting, make sure that all parameters, including the default values, are exactly the same or else the model's hash might change.\n\n\n#### `@Field.Coded`\n\nThe `@Field.Coded` property wrapper is used for binary-codable values. This is the new counterpart, **not replacement**, for `Transformable.Required` and `Transformable.Optional` properties. `@Field.Coded` also supports other encodings such as JSON and custom binary converters.\n\n\u003e ‼️ The current `Transformable.Required` and `Transformable.Optional` mechanism have no safe one-to-one conversion to `@Field.Coded`. Please use `@Field.Coded` only for newly added attributes.\n\n\u003ctable\u003e\n\u003ctr\u003e\u003cth\u003eBefore\u003c/th\u003e\u003cth\u003e\u003cpre lang=swift\u003e@Field.Coded\u003c/pre\u003e\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Vehicle: CoreStoreObject {\n    \u003cbr /\u003e\n    let color = Transformable.Optional\u0026lt;UIColor\u0026gt;(\"color\", initial: .white)\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Vehicle: CoreStoreObject {\n    \u003cbr /\u003e\n    @Field.Coded(\"color\", coder: FieldCoders.NSCoding.self)\n    var color: UIColor? = .white\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\nBuilt-in encoders such as `FieldCoders.NSCoding`, `FieldCoders.Json`, and `FieldCoders.Plist` are available, and custom encoding/decoding is also supported:\n```swift\nclass Person: CoreStoreObject {\n    \n    struct CustomInfo: Codable {\n        // ...\n    }\n    \n    @Field.Coded(\"otherInfo\", coder: FieldCoders.Json.self)\n    var otherInfo: CustomInfo?\n    \n    @Field.Coded(\n        \"photo\",\n        coder: {\n            encode: { $0.toData() },\n            decode: { Photo(fromData: $0) }\n        }\n    )\n    var photo: Photo?\n}\n```\n\n\u003e ‼️**Important:** Any changes in the encoders/decoders are not reflected in the `VersionLock`, so make sure that the encoder and decoder logic is compatible for all versions of your persistent store.\n\n#### `@Field.Relationship`\n\nThe `@Field.Relationship` property wrapper is used for link relationships with other `CoreStoreObject`s. This is the replacement for `Relationship.ToOne`, `Relationship.ToManyOrdered`, and `Relationship.ToManyUnordered` properties.\n\nThe type of relationship is determined by the `@Field.Relationship`  generic type:\n\n- `Optional\u003cT\u003e` : To-one relationship\n- `Array\u003cT\u003e` : To-many ordered relationship\n- `Set\u003cT\u003e` : To-many unordered relationship\n\n\u003ctable\u003e\n\u003ctr\u003e\u003cth\u003eBefore\u003c/th\u003e\u003cth\u003e\u003cpre lang=swift\u003e@Field.Stored\u003c/pre\u003e\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Pet: CoreStoreObject {\n    \u003cbr /\u003e\n    let master = Relationship.ToOne\u0026lt;Person\u0026gt;(\"master\")\n}\nclass Person: CoreStoreObject {\n    \u003cbr /\u003e\n    let pets: Relationship.ToManyUnordered\u0026lt;Pet\u0026gt;(\"pets\", inverse: \\.$master)\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003ctd\u003e\u003cpre lang=swift\u003e\nclass Pet: CoreStoreObject {\n    \u003cbr /\u003e\n    @Field.Relationship(\"master\")\n    var master: Person?\n}\nclass Person: CoreStoreObject {\n    \u003cbr /\u003e\n    @Field.Relationship(\"pets\", inverse: \\.$master)\n    var pets: Set\u0026lt;Pet\u0026gt;\n}\n\u003c/pre\u003e\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n\u003e ⚠️ When converting, make sure that all parameters, including the default values, are exactly the same or else the model's hash might change.\n\nAlso note how `Relationship`s are linked statically with the `inverse:` argument. **All relationships are required to have an \"inverse\" relationship**. Unfortunately, due to Swift compiler limitation we can declare the `inverse:` on only one of the relationship-pair.\n\n#### `@Field` usage notes \n\n**Accessor syntax**\n\nWhen using key-path utilities, properties using `@Field` property wrappers need to use the `$` syntax:\n\n- Before: `From\u003cPerson\u003e.where(\\.title == \"Mr.\")`\n- After: `From\u003cPerson\u003e.where(\\.$title == \"Mr.\")`\n\nThis applies to property access using `ObjectPublisher`s and `ObjectSnapshot`s.\n\n- Before: `let name = personSnapshot.name`\n- After: `let name = personSnapshot.$name`\n\n\n**Default values vs. Initial values**\n\nOne common mistake when assigning default values to `CoreStoreObject` properties is to assign it a value and expect it to be evaluated whenever an object is created:\n\n```swift\n// ❌\nclass Person: CoreStoreObject {\n\n    @Field.Stored(\"identifier\")\n    var identifier: UUID = UUID() // Wrong!\n    \n    @Field.Stored(\"createdDate\")\n    var createdDate: Date = Date() // Wrong!\n}\n```\n\nThis default value will be evaluated only when the `DataStack` sets up the schema, and all instances will end up having the same values. This syntax for \"default values\" are usually used only for actual reasonable constant values, or sentinel values such as `\"\"` or `0`.\n\nFor actual \"initial values\", `@Field.Stored` and `@Field.Coded` now supports dynamic evaluation during object creation via the `dynamicInitialValue:` argument:\n\n```swift\n// ✅\nclass Person: CoreStoreObject {\n\n    @Field.Stored(\"identifier\", dynamicInitialValue: { UUID() })\n    var identifier: UUID\n    \n    @Field.Stored(\"createdDate\", dynamicInitialValue: { Date() })\n    var createdDate: Date\n}\n```\nWhen using this feature, a \"default value\" should not be assigned (i.e. no `=` expression). \n\n\n### `VersionLock`s\n\nWhile it is convenient to be able to declare entities only in code, it is worrying that we might accidentally change the `CoreStoreObject`'s properties and break our users' model version history. For this, the `CoreStoreSchema` allows us to \"lock\" our properties to a particular configuration. Any changes to that `VersionLock` will raise an assertion failure during the `CoreStoreSchema` initialization, so you can then look for the commit which changed the `VersionLock` hash.\n\nTo use `VersionLock`s, create the `CoreStoreSchema`, run the app, and look for a similar log message that is automatically printed to the console:\n\n\u003cimg width=\"700\" alt=\"VersionLock\" src=\"https://cloud.githubusercontent.com/assets/3029684/26525632/757f1bd0-4398-11e7-9795-4132a2df0538.png\" /\u003e\n\nCopy this dictionary value and use it as the `versionLock:` argument of the `CoreStoreSchema` initializer:\n```swift\nCoreStoreSchema(\n    modelVersion: \"V1\",\n    entities: [\n        Entity\u003cAnimal\u003e(\"Animal\", isAbstract: true),\n        Entity\u003cDog\u003e(\"Dog\"),\n        Entity\u003cPerson\u003e(\"Person\"),\n    ],\n    versionLock: [\n        \"Animal\": [0x1b59d511019695cf, 0xdeb97e86c5eff179, 0x1cfd80745646cb3, 0x4ff99416175b5b9a],\n        \"Dog\": [0xe3f0afeb109b283a, 0x29998d292938eb61, 0x6aab788333cfc2a3, 0x492ff1d295910ea7],\n        \"Person\": [0x66d8bbfd8b21561f, 0xcecec69ecae3570f, 0xc4b73d71256214ef, 0x89b99bfe3e013e8b]\n    ]\n)\n```\nYou can also get this hash after the `DataStack` has been fully set up by printing to the console:\n```swift\nprint(CoreStoreDefaults.dataStack.modelSchema.printCoreStoreSchema())\n```\n\nOnce the version lock is set, any changes in the properties or to the model will trigger an assertion failure similar to this:\n\n\u003cimg width=\"700\" alt=\"VersionLock failure\" src=\"https://cloud.githubusercontent.com/assets/3029684/26525666/92f46f0c-4399-11e7-9395-4379f6f20876.png\" /\u003e\n\n## Reactive Programming\n### RxSwift\nRxSwift utilities are available through the [RxCoreStore](https://github.com/JohnEstropia/RxCoreStore) external module.\n\n### Combine\n\nCombine publishers are available from the `DataStack`, `ListPublisher`, and `ObjectPublisher`'s `.reactive` namespace property.\n\n#### `DataStack.reactive`\n\nAdding a storage through `DataStack.reactive.addStorage(_:)` returns a publisher that reports a `MigrationProgress` `enum` value. The `.migrating` value is only emitted if the storage goes through a migration. Refer to the [Setting up](#setting-up) section for details on the storage setup process itself.\n\n```swift\ndataStack.reactive\n    .addStorage(\n        SQLiteStore(fileName: \"core_data.sqlite\")\n    )\n    .sink(\n        receiveCompletion: { result in\n            // ...\n        },\n        receiveValue: { (progress) in\n            print(\"\\(round(progress.fractionCompleted * 100)) %\") // 0.0 ~ 1.0\n            switch progress {\n            case .migrating(let storage, let nsProgress):\n                // ...\n            case .finished(let storage, let migrationRequired):\n                // ...\n            }\n        }\n    )\n    .store(in: \u0026cancellables)\n```\n\n[Transactions](#saving-and-processing-transactions) are also available as publishers through `DataStack.reactive.perform(_:)`, which returns a Combine `Future` that emits any type returned from the closure parameter:\n```swift\ndataStack.reactive\n    .perform(\n        asynchronous: { (transaction) -\u003e (inserted: Set\u003cNSManagedObject\u003e, deleted: Set\u003cNSManagedObject\u003e) in\n\n            // ...\n            return (\n                transaction.insertedObjects(),\n                transaction.deletedObjects()\n            )\n        }\n    )\n    .sink(\n        receiveCompletion: { result in\n            // ...\n        },\n        receiveValue: { value in\n            let inserted = dataStack.fetchExisting(value0.inserted)\n            let deleted = dataStack.fetchExisting(value0.deleted)\n            // ...\n        }\n    )\n    .store(in: \u0026cancellables)\n```\n\nFor importing convenience, `ImportableObject` and `ImportableUniqueObjects` can be imported directly through `DataStack.reactive.import[Unique]Object(_:source:)` and `DataStack.reactive.import[Unique]Objects(_:sourceArray:)` without having to create a transaction block. In this case the publisher emits objects that are already usable directly from the main queue:\n```swift\ndataStack.reactive\n    .importUniqueObjects(\n        Into\u003cPerson\u003e(),\n        sourceArray: [\n            [\"name\": \"John\"],\n            [\"name\": \"Bob\"],\n            [\"name\": \"Joe\"]\n        ]\n    )\n    .sink(\n        receiveCompletion: { result in\n            // ...\n        },\n        receiveValue: { (people) in\n            XCTAssertEqual(people?.count, 3)\n            // ...\n        }\n    )\n    .store(in: \u0026cancellables)\n```\n\n#### `ListPublisher.reactive`\n\n`ListPublisher`s can be used to emit `ListSnapshot`s through Combine using `ListPublisher.reactive.snapshot(emitInitialValue:)`. The snapshot values are emitted in the main queue:\n```swift\nlistPublisher.reactive\n    .snapshot(emitInitialValue: true)\n    .sink(\n        receiveCompletion: { result in\n            // ...\n        },\n        receiveValue: { (listSnapshot) in\n            dataSource.apply(\n                listSnapshot,\n                animatingDifferences: true\n            )\n        }\n    )\n    .store(in: \u0026cancellables)\n```\n\n#### `ObjectPublisher.reactive`\n\n`ObjectPublisher`s can be used to emit `ObjectSnapshot`s through Combine using `ObjectPublisher.reactive.snapshot(emitInitialValue:)`. The snapshot values are emitted in the main queue:\n```swift\nobjectPublisher.reactive\n    .snapshot(emitInitialValue: true)\n    .sink(\n        receiveCompletion: { result in\n            // ...\n        },\n        receiveValue: { (objectSnapshot) in\n            tableViewCell.setObject(objectSnapshot)\n        }\n    )\n    .store(in: \u0026tableViewCell.cancellables)\n```\n\n\n## SwiftUI Utilities\n\nObserving list and object changes in SwiftUI can be done through a couple of approaches. One is by creating [views that autoupdates their contents](#swiftui-views), or by declaring [property wrappers that trigger view updates](#swiftui-property-wrappers). Both approaches are implemented almost the same internally, but this lets you be flexible depending on the structure of your custom `View`s.\n\n### SwiftUI Views\n\nCoreStore provides `View` containers that automatically update their contents when data changes.\n\n#### `ListReader`\n\nA `ListReader` observes changes to a `ListPublisher` and creates its content views dynamically. The builder closure receives a `ListSnapshot` value that can be used to create the contents:\n```swift\nlet people: ListPublisher\u003cPerson\u003e\n\nvar body: some View {\n   List {\n       ListReader(self.people) { listSnapshot in\n           ForEach(objectIn: listSnapshot) { person in\n               // ...\n           }\n       }\n   }\n   .animation(.default)\n}\n```\nAs shown above, a typical use case is to use it together with CoreStore's [`ForEach` extensions](#foreach).\n\nA `KeyPath` can also be optionally provided to extract specific properties of the `ListSnapshot`:\n```swift\nlet people: ListPublisher\u003cPerson\u003e\n\nvar body: some View {\n    ListReader(self.people, keyPath: \\.count) { count in\n        Text(\"Number of members: \\(count)\")\n    }\n}\n```\n\n#### `ObjectReader`\n\nAn `ObjectReader` observes changes to an `ObjectPublisher` and creates its content views dynamically. The builder closure receives an `ObjectSnapshot` value that can be used to create the contents:\n```swift\nlet person: ObjectPublisher\u003cPerson\u003e\n\nvar body: some View {\n   ObjectReader(self.person) { objectSnapshot in\n       // ...\n   }\n   .animation(.default)\n}\n```\n\nA `KeyPath` can also be optionally provided to extract specific properties of the `ObjectSnapshot`:\n```swift\nlet person: ObjectPublisher\u003cPerson\u003e\n\nvar body: some View {\n    ObjectReader(self.person, keyPath: \\.fullName) { fullName in\n        Text(\"Name: \\(fullName)\")\n    }\n}\n```\n\nBy default, an `ObjectReader` does not create its views wheen the object observed is deleted from the store. In those cases, the `placeholder:` argument can be used to provide a custom `View` to display when the object is deleted:\n```swift\nlet person: ObjectPublisher\u003cPerson\u003e\n\nvar body: some View {\n   ObjectReader(\n       self.person,\n       content: { objectSnapshot in\n           // ...\n       },\n       placeholder: { Text(\"Record not found\") }\n   )\n}\n```\n\n### SwiftUI Property Wrappers\n\nAs an alternative to `ListReader` and `ObjectReader`, CoreStore also provides property wrappers that trigger view updates when the data changes.\n\n#### `ListState`\n\nA `@ListState` property exposes a `ListSnapshot` value that automatically updates to the latest changes.\n```swift\n@ListState\nvar people: ListSnapshot\u003cPerson\u003e\n\ninit(listPublisher: ListPublisher\u003cPerson\u003e) {\n   self._people = .init(listPublisher)\n}\n\nvar body: some View {\n   List {\n       ForEach(objectIn: self.people) { objectSnapshot in\n           // ...\n       }\n   }\n   .animation(.default)\n}\n```\nAs shown above, a typical use case is to use it together with CoreStore's [`ForEach` extensions](#foreach).\n\nIf a `ListPublisher` instance is not available yet, the fetch can be done inline by providing the fetch clauses and the `DataStack` instance. By doing so the property can be declared without an initial value:\n```swift\n@ListState(\n    From\u003cPerson\u003e()\n        .sectionBy(\\.age)\n        .where(\\.isMember == true)\n        .orderBy(.ascending(\\.lastName))\n)\nvar people: ListSnapshot\u003cPerson\u003e\n\nvar body: some View {\n    List {\n        ForEach(sectionIn: self.people) { section in\n            Section(header: Text(section.sectionID)) {\n                ForEach(objectIn: section) { person in\n                    // ...\n                }\n            }\n        }\n    }\n    .animation(.default)\n}\n```\n\nFor other initialization variants, refer to the *ListState.swift*  source documentations.\n\n\n#### `ObjectState`\n\nAn `@ObjectState` property exposes an optional `ObjectSnapshot` value that automatically updates to the latest changes.\n```swift\n@ObjectState\nvar person: ObjectSnapshot\u003cPerson\u003e?\n\ninit(objectPublisher: ObjectPublisher\u003cPerson\u003e) {\n   self._person = .init(objectPublisher)\n}\n\nvar body: some View {\n   HStack {\n       if let person = self.person {\n           AsyncImage(person.$avatarURL)\n           Text(person.$fullName)\n       }\n       else {\n           Text(\"Record removed\")\n       }\n   }\n}\n```\nAs shown above, the property's value will be `nil` if the object has been deleted, so this can be used to display placeholders if needed.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJohnEstropia%2FCoreStore","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FJohnEstropia%2FCoreStore","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJohnEstropia%2FCoreStore/lists"}