mirror of
https://github.com/JohnEstropia/CoreStore.git
synced 2026-01-15 21:53:39 +01:00
1 line
56 KiB
JSON
1 line
56 KiB
JSON
{"name":"Corestore","tagline":"Unleashing the real power of Core Data with the elegance and safety of Swift","body":"\r\n\r\n[](https://travis-ci.org/JohnEstropia/CoreStore)\r\n[](http://cocoadocs.org/docsets/CoreStore)\r\n[](http://cocoadocs.org/docsets/CoreStore)\r\n[](https://raw.githubusercontent.com/JohnEstropia/CoreStore/master/LICENSE)\r\n[](https://github.com/Carthage/Carthage)\r\n\r\nUnleashing the real power of Core Data with the elegance and safety of Swift\r\n\r\n* Swift 2.2 (Xcode 7.3)\r\n* iOS 8+ / OSX 10.10+ / watchOS 2.0+ / tvOS 9.0+\r\n\r\n<iframe src=\"https://ghbtns.com/github-btn.html?user=JohnEstropia&repo=CoreStore&type=star&count=true&size=large\" frameborder=\"0\" scrolling=\"0\" width=\"160px\" height=\"30px\"></iframe>\r\n\r\n## What CoreStore does better:\r\n\r\n- **Heavily supports multiple persistent stores per data stack**, just the way *.xcdatamodeld* files are designed to. CoreStore will also manage one data stack by default, but you can create and manage as many as you need.\r\n- **Progressive Migrations!** Just tell the data stack the sequence of model versions and CoreStore will automatically use progressive migrations if needed on stores added to that stack.\r\n- Ability to **plug-in your own logging framework**\r\n- Gets around a limitation 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 are **free to name entities and their class names independently**.\r\n- Provides type-safe, easy to configure **observers to replace `NSFetchedResultsController` and KVO**\r\n- Exposes **API not just for fetching, but also for querying aggregates and property values**\r\n- Makes it hard to fall into common concurrency mistakes. All `NSManagedObjectContext` tasks are encapsulated into **safer, higher-level abstractions** without sacrificing flexibility and customizability.\r\n- Exposes clean and convenient API designed around **Swift’s code elegance and type safety**.\r\n- **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.\r\n- **Efficient importing utilities!**\r\n\r\n**[Vote for the next feature!](http://goo.gl/RIiHMP)**\r\n\r\n\r\n\r\n## Contents\r\n\r\n- [TL;DR (a.k.a. sample codes)](#tldr-aka-sample-codes)\r\n- [Architecture](#architecture)\r\n- CoreStore Tutorials (All of these have demos in the **CoreStoreDemo** app project!)\r\n - [Setting up](#setting-up)\r\n - [Migrations](#migrations)\r\n - [Progressive migrations](#progressive-migrations)\r\n - [Forecasting migrations](#forecasting-migrations)\r\n - [Saving and processing transactions](#saving-and-processing-transactions)\r\n - [Transaction types](#transaction-types)\r\n - [Asynchronous transactions](#asynchronous-transactions)\r\n - [Synchronous transactions](#synchronous-transactions)\r\n - [Unsafe transactions](#unsafe-transactions)\r\n - [Creating objects](#creating-objects)\r\n - [Updating objects](#updating-objects)\r\n - [Deleting objects](#deleting-objects)\r\n - [Passing objects safely](#passing-objects-safely)\r\n - [Importing data](#importing-data)\r\n - [Fetching and querying](#fetching-and-querying)\r\n - [`From` clause](#from-clause)\r\n - [Fetching](#fetching)\r\n - [`Where` clause](#where-clause)\r\n - [`OrderBy` clause](#orderby-clause)\r\n - [`Tweak` clause](#tweak-clause)\r\n - [Querying](#querying)\r\n - [`Select<T>` clause](#selectt-clause)\r\n - [`GroupBy` clause](#groupby-clause)\r\n - [Logging and error handling](#logging-and-error-handling)\r\n - [Observing changes and notifications](#observing-changes-and-notifications) (unavailable on OSX)\r\n - [Observe a single object](#observe-a-single-object)\r\n - [Observe a list of objects](#observe-a-list-of-objects)\r\n- [Roadmap](#roadmap)\r\n- [Installation](#installation)\r\n- [Changesets](#changesets)\r\n - [Upgrading from v0.2.0 to 1.0.0](#upgrading-from-v020-to-100)\r\n\r\n\r\n\r\n## TL;DR (a.k.a. sample codes)\r\n\r\nSetting-up with progressive migration support:\r\n```swift\r\nCoreStore.defaultStack = DataStack(\r\n modelName: \"MyStore\",\r\n migrationChain: [\"MyStore\", \"MyStoreV2\", \"MyStoreV3\"]\r\n)\r\n```\r\n\r\nAdding a store:\r\n```swift\r\ntry CoreStore.addSQLiteStore(\r\n fileName: \"MyStore.sqlite\",\r\n completion: { (result) -> Void in\r\n // ...\r\n }\r\n)\r\n```\r\n\r\nStarting transactions:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let person = transaction.create(Into(MyPersonEntity))\r\n person.name = \"John Smith\"\r\n person.age = 42\r\n\r\n transaction.commit { (result) -> Void in\r\n switch result {\r\n case .Success(let hasChanges): print(\"success!\")\r\n case .Failure(let error): print(error)\r\n }\r\n }\r\n}\r\n```\r\n\r\nFetching objects:\r\n```swift\r\nlet people = CoreStore.fetchAll(From(MyPersonEntity))\r\n```\r\n```swift\r\nlet people = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(\"age > 30\"),\r\n OrderBy(.Ascending(\"name\"), .Descending(\"age\")),\r\n Tweak { (fetchRequest) -> Void in\r\n fetchRequest.includesPendingChanges = false\r\n }\r\n)\r\n```\r\n\r\nQuerying values:\r\n```swift\r\nlet maxAge = CoreStore.queryValue(\r\n From(MyPersonEntity),\r\n Select<Int>(.Maximum(\"age\"))\r\n)\r\n```\r\n\r\nBut really, there's a reason I wrote this huge README. Read up on the details!\r\n\r\nCheck out the **CoreStoreDemo** app project for sample codes as well!\r\n\r\n\r\n\r\n## Architecture\r\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.\r\n\r\nIf you are already familiar with the inner workings of CoreData, here is a mapping of `CoreStore` abstractions:\r\n\r\n| *Core Data* | *CoreStore* |\r\n| --- | --- |\r\n| `NSManagedObjectModel` / `NSPersistentStoreCoordinator`<br />(.xcdatamodeld file) | `DataStack` |\r\n| `NSPersistentStore`<br />(\"Configuration\"s in the .xcdatamodeld file) | `DataStack` configuration<br />(multiple sqlite / in-memory stores per stack) |\r\n| `NSManagedObjectContext` | `BaseDataTransaction` subclasses<br />(`SynchronousDataTransaction`, `AsynchronousDataTransaction`, `UnsafeDataTransaction`) |\r\n\r\nPopular libraries [RestKit](https://github.com/RestKit/RestKit) and [MagicalRecord](https://github.com/magicalpanda/MagicalRecord) set up their `NSManagedObjectContext`s this way:\r\n\r\n<img src=\"https://cloud.githubusercontent.com/assets/3029684/6734049/40579660-ce99-11e4-9d38-829877386afb.png\" alt=\"nested contexts\" height=271 />\r\n\r\nNesting context saves from child context to the root context ensures maximum data integrity between contexts without blocking the main queue. But as <a href=\"http://floriankugler.com/2013/04/29/concurrent-core-data-stack-performance-shootout/\">Florian Kugler's investigation</a> found out, merging contexts is still by far faster than saving nested contexts. CoreStore's `DataStack` takes the best of both worlds by treating the main `NSManagedObjectContext` as a read-only context, and only allows changes to be made within *transactions* on the child context:\r\n\r\n<img src=\"https://cloud.githubusercontent.com/assets/3029684/6734050/4078b642-ce99-11e4-95ea-c0c1d24fbe80.png\" alt=\"nested contexts and merge hybrid\" height=212 />\r\n\r\nThis allows for a butter-smooth main thread, while still taking advantage of safe nested contexts.\r\n\r\n\r\n\r\n## Setting up\r\nThe simplest way to initialize CoreStore is to add a default store to the default stack:\r\n```swift\r\ndo {\r\n try CoreStore.addSQLiteStoreAndWait()\r\n}\r\ncatch {\r\n // ...\r\n}\r\n```\r\nThis one-liner does the following:\r\n- Triggers the lazy-initialization of `CoreStore.defaultStack` with a default `DataStack`\r\n- Sets up the stack's `NSPersistentStoreCoordinator`, the root saving `NSManagedObjectContext`, and the read-only main `NSManagedObjectContext`\r\n- Adds an SQLite store in the *\"Application Support/<bundle id>\"* directory (or the *\"Caches/<bundle id>\"* directory on tvOS) with the file name *\"[App bundle name].sqlite\"*\r\n- Creates and returns the `NSPersistentStore` instance on success, or an `NSError` on failure\r\n\r\nFor most cases, this configuration is usable as it is. But for more hardcore settings, refer to this extensive example:\r\n```swift\r\nlet dataStack = DataStack(\r\n modelName: \"MyModel\", // loads from the \"MyModel.xcdatamodeld\" file\r\n migrationChain: [\"MyStore\", \"MyStoreV2\", \"MyStoreV3\"] // model versions for progressive migrations\r\n)\r\n\r\ndo {\r\n // creates an in-memory store with entities from the \"Config1\" configuration in the .xcdatamodeld file\r\n let persistentStore = try dataStack.addInMemoryStoreAndWait(configuration: \"Config1\") // persistentStore is an NSPersistentStore instance\r\n print(\"Successfully created an in-memory store: \\(persistentStore)\"\r\n}\r\ncatch {\r\n print(\"Failed creating an in-memory store with error: \\(error as NSError)\"\r\n}\r\n\r\ndo {\r\n try dataStack.addSQLiteStore(\r\n fileURL: sqliteFileURL, // set the target file URL for the sqlite file\r\n configuration: \"Config2\", // use entities from the \"Config2\" configuration in the .xcdatamodeld file\r\n resetStoreOnModelMismatch: true,\r\n completion: { (result) -> Void in\r\n switch result {\r\n case .Success(let persistentStore):\r\n print(\"Successfully added sqlite store: \\(persistentStore)\"\r\n case .Failure(let error):\r\n print(\"Failed adding sqlite store with error: \\(error)\"\r\n }\r\n }\r\n )\r\n}\r\ncatch {\r\n print(\"Failed adding sqlite store with error: \\(error as NSError)\"\r\n}\r\n\r\nCoreStore.defaultStack = dataStack // pass the dataStack to CoreStore for easier access later on\r\n```\r\n\r\n(If you have never heard of \"Configurations\", you'll find them in your *.xcdatamodeld* file)\r\n<img src=\"https://cloud.githubusercontent.com/assets/3029684/8333192/e52cfaac-1acc-11e5-9902-08724f9f1324.png\" alt=\"xcode configurations screenshot\" height=212 />\r\n\r\nIn our sample code above, note that you don't need to do the `CoreStore.defaultStack = dataStack` line. You can just as well hold a reference to the `DataStack` like below and call all its instance methods directly:\r\n```swift\r\nclass MyViewController: UIViewController {\r\n let dataStack = DataStack(modelName: \"MyModel\")\r\n override func viewDidLoad() {\r\n super.viewDidLoad()\r\n do {\r\n try self.dataStack.addSQLiteStoreAndWait()\r\n }\r\n catch { // ...\r\n }\r\n }\r\n func methodToBeCalledLaterOn() {\r\n let objects = self.dataStack.fetchAll(From(MyEntity))\r\n print(objects)\r\n }\r\n}\r\n```\r\nThe difference is when you set the stack as the `CoreStore.defaultStack`, you can call the stack's methods directly from `CoreStore` itself:\r\n```swift\r\nclass MyViewController: UIViewController {\r\n override func viewDidLoad() {\r\n super.viewDidLoad()\r\n do {\r\n try CoreStore.addSQLiteStoreAndWait()\r\n }\r\n catch { // ...\r\n }\r\n }\r\n func methodToBeCalledLaterOn() {\r\n let objects = CoreStore.fetchAll(From(MyEntity))\r\n print(objects)\r\n }\r\n}\r\n```\r\n\r\n\r\n## Migrations\r\nSo far we have only seen `addSQLiteStoreAndWait(...)` used to initialize our persistent store. As the method name's \"AndWait\" suffix suggests, this method blocks so it should not do long tasks such as store migrations (in fact CoreStore won't even attempt to, and any model mismatch will be reported as an error). If migrations are expected, the asynchronous variant `addSQLiteStore(... completion:)` method should be used instead:\r\n```swift\r\ndo {\r\n let progress: NSProgress? = try dataStack.addSQLiteStore(\r\n fileName: \"MyStore.sqlite\",\r\n configuration: \"Config2\",\r\n completion: { (result) -> Void in\r\n switch result {\r\n case .Success(let persistentStore):\r\n print(\"Successfully added sqlite store: \\(persistentStore)\")\r\n case .Failure(let error):\r\n print(\"Failed adding sqlite store with error: \\(error)\")\r\n }\r\n }\r\n )\r\n}\r\ncatch {\r\n print(\"Failed adding sqlite store with error: \\(error as NSError)\"\r\n}\r\n```\r\nThe `completion` block reports a `PersistentStoreResult` that indicates success or failure.\r\n\r\n`addSQLiteStore(...)` throws an error if the store at the specified URL conflicts with an existing store in the `DataStack`, or if an existing sqlite file could not be read. If an error is thrown, the `completion` block will not be executed.\r\n\r\nNotice that this method also returns an optional `NSProgress`. 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 *NSProgress+Convenience.swift*:\r\n```swift\r\nprogress?.setProgressHandler { [weak self] (progress) -> Void in\r\n self?.progressView?.setProgress(Float(progress.fractionCompleted), animated: true)\r\n self?.percentLabel?.text = progress.localizedDescription // \"50% completed\"\r\n self?.stepLabel?.text = progress.localizedAdditionalDescription // \"0 of 2\"\r\n}\r\n```\r\nThis closure is executed on the main thread so UIKit calls can be done safely.\r\n\r\n\r\n### Progressive migrations\r\nBy default, CoreStore uses Core Data's default automatic migration mechanism. In other words, CoreStore will try to migrate the existing persistent store to the *.xcdatamodeld* file's current model version. If no mapping model is found from the store's version to the data model's version, CoreStore gives up and reports an error.\r\n\r\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:\r\n```swift\r\nlet dataStack = DataStack(migrationChain: \r\n [\"MyAppModel\", \"MyAppModelV2\", \"MyAppModelV3\", \"MyAppModelV4\"])\r\n```\r\nThe most common usage is to pass in the *.xcdatamodeld* version names in increasing order as above.\r\n\r\nFor more complex migration paths, you can also pass in a version tree that maps the key-values to the source-destination versions:\r\n```swift\r\nlet dataStack = DataStack(migrationChain: [\r\n \"MyAppModel\": \"MyAppModelV3\",\r\n \"MyAppModelV2\": \"MyAppModelV4\",\r\n \"MyAppModelV3\": \"MyAppModelV4\"\r\n])\r\n```\r\nThis allows for different migration paths depending on the starting version. The example above resolves to the following paths:\r\n- MyAppModel-MyAppModelV3-MyAppModelV4\r\n- MyAppModelV2-MyAppModelV4\r\n- MyAppModelV3-MyAppModelV4\r\n\r\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 .xcdatamodel's current version as the final version):\r\n```swift\r\nlet dataStack = DataStack(migrationChain: nil)\r\n```\r\n\r\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:\r\n- a version appears twice in an array\r\n- a version appears twice as a key in a dictionary literal\r\n- a loop is found in any of the paths\r\n\r\nOne important thing to remember is that **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.\r\n\r\n\r\n### Forecasting migrations\r\n\r\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 `requiredMigrationsForSQLiteStore(...)` method you can use to inspect a persistent store before you actually call `addSQLiteStore(...)`:\r\n```swift\r\ndo {\r\n let migrationTypes: [MigrationType] = CoreStore.requiredMigrationsForSQLiteStore(fileName: \"MyStore.sqlite\")\r\n if migrationTypes.count > 1\r\n || (migrationTypes.filter { $0.isHeavyweightMigration }.count) > 0 {\r\n // ... Show special waiting screen\r\n }\r\n else if migrationTypes.count > 0 {\r\n // ... Show simple activity indicator\r\n }\r\n else {\r\n // ... Do nothing\r\n }\r\n\r\n CoreStore.addSQLiteStore(/* ... */)\r\n}\r\ncatch {\r\n // ...\r\n}\r\n```\r\n`requiredMigrationsForSQLiteStore(...)` returns an array of `MigrationType`s, where each item in the array may be either of the following values:\r\n```swift\r\ncase Lightweight(sourceVersion: String, destinationVersion: String)\r\ncase Heavyweight(sourceVersion: String, destinationVersion: String)\r\n```\r\nEach `MigrationType` indicates the migration type for each step in the `MigrationChain`. Use these information as fit for your app.\r\n\r\n\r\n\r\n## Saving and processing transactions\r\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:\r\n```swift\r\nlet dataStack = self.dataStack\r\ndataStack.beginAsynchronous { (transaction) -> Void in\r\n // make changes\r\n transaction.commit()\r\n}\r\n```\r\nor for the default stack, directly from `CoreStore`:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n // make changes\r\n transaction.commit()\r\n}\r\n```\r\nThe `commit()` method saves the changes to the persistent store. If `commit()` is not called when the transaction block completes, all changes within the transaction is discarded.\r\n\r\nThe examples above use `beginAsynchronous(...)`, but there are actually 3 types of transactions at your disposal: *asynchronous*, *synchronous*, and *unsafe*.\r\n\r\n### Transaction types\r\n\r\n#### Asynchronous transactions\r\nare spawned from `beginAsynchronous(...)`. This method returns immediately and executes its closure from a background serial queue:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n // make changes\r\n transaction.commit()\r\n}\r\n```\r\nTransactions created from `beginAsynchronous(...)` are instances of `AsynchronousDataTransaction`.\r\n\r\n#### Synchronous transactions\r\nare created from `beginSynchronous(...)`. While the syntax is similar to its asynchronous counterpart, `beginSynchronous(...)` waits for its transaction block to complete before returning:\r\n```swift\r\nCoreStore.beginSynchronous { (transaction) -> Void in\r\n // make changes\r\n transaction.commit()\r\n} \r\n```\r\n`transaction` above is a `SynchronousDataTransaction` instance.\r\n\r\nSince `beginSynchronous(...)` 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.\r\n\r\n#### Unsafe transactions\r\nare special in that they do not enclose updates within a closure:\r\n```swift\r\nlet transaction = CoreStore.beginUnsafe()\r\n// make changes\r\ndownloadJSONWithCompletion({ (json) -> Void in\r\n\r\n // make other changes\r\n transaction.commit()\r\n})\r\ndownloadAnotherJSONWithCompletion({ (json) -> Void in\r\n\r\n // make some other changes\r\n transaction.commit()\r\n})\r\n```\r\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.\"\r\n\r\nAs the above example also shows, only unsafe transactions are allowed to call `commit()` multiple times; doing so with synchronous and asynchronous transactions will trigger an assert. \r\n\r\n\r\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.\r\n\r\n### Creating objects\r\n\r\nThe `create(...)` method accepts an `Into` clause which specifies the entity for the object you want to create:\r\n```swift\r\nlet person = transaction.create(Into(MyPersonEntity))\r\n```\r\nWhile the syntax is straightforward, CoreStore does not just naively insert a new object. This single line does the following:\r\n- Checks that the entity type exists in any of the transaction's parent persistent store\r\n- If the entity belongs to only one persistent store, a new object is inserted into that store and returned from `create(...)`\r\n- If the entity does not belong to any store, an assert will be triggered. **This is a programmer error and should never occur in production code.**\r\n- If the entity belongs to multiple stores, an assert will be triggered. **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).\r\n\r\nIf the entity exists in multiple configurations, you need to provide the configuration name for the destination persistent store:\r\n\r\n let person = transaction.create(Into<MyPersonEntity>(\"Config1\"))\r\n\r\nor if the persistent store is the auto-generated \"Default\" configuration, specify `nil`:\r\n\r\n let person = transaction.create(Into<MyPersonEntity>(nil))\r\n\r\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. \r\n\r\n### Updating objects\r\n\r\nAfter creating an object from the transaction, you can simply update its properties as normal:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let person = transaction.create(Into(MyPersonEntity))\r\n person.name = \"John Smith\"\r\n person.age = 30\r\n transaction.commit()\r\n}\r\n```\r\nTo update an existing object, fetch the object's instance from the transaction:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let person = transaction.fetchOne(\r\n From(MyPersonEntity),\r\n Where(\"name\", isEqualTo: \"Jane Smith\")\r\n )\r\n person.age = person.age + 1\r\n transaction.commit()\r\n}\r\n```\r\n*(For more about fetching, see [Fetching and querying](#fetching-and-querying))*\r\n\r\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:\r\n```swift\r\nlet jane: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n // WRONG: jane.age = jane.age + 1\r\n // RIGHT:\r\n let jane = transaction.edit(jane)! // using the same variable name protects us from misusing the non-transaction instance\r\n jane.age = jane.age + 1\r\n transaction.commit()\r\n}\r\n```\r\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:\r\n```swift\r\nlet jane: MyPersonEntity = // ...\r\nlet john: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n // WRONG: jane.friends = [john]\r\n // RIGHT:\r\n let jane = transaction.edit(jane)!\r\n let john = transaction.edit(john)!\r\n jane.friends = NSSet(array: [john])\r\n transaction.commit()\r\n}\r\n```\r\n\r\n### Deleting objects\r\n\r\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):\r\n```swift\r\nlet john: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n transaction.delete(john)\r\n transaction.commit()\r\n}\r\n```\r\nor several objects at once:\r\n```swift\r\nlet john: MyPersonEntity = // ...\r\nlet jane: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n transaction.delete(john, jane)\r\n // transaction.delete([john, jane]) is also allowed\r\n transaction.commit()\r\n}\r\n```\r\nIf you do not have references yet to the objects to be deleted, transactions have a `deleteAll(...)` method you can pass a query to:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n transaction.deleteAll(\r\n From(MyPersonEntity)\r\n Where(\"age > 30\")\r\n )\r\n transaction.commit()\r\n}\r\n```\r\n\r\n### Passing objects safely\r\n\r\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:\r\n```swift\r\nlet jane: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jane = transaction.edit(jane)!\r\n jane.age = jane.age + 1\r\n transaction.commit()\r\n}\r\n```\r\nBut `CoreStore`, `DataStack` and `BaseDataTransaction` have a very flexible `fetchExisting(...)` method that you can pass instances back and forth with:\r\n```swift\r\nlet jane: MyPersonEntity = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jane = transaction.fetchExisting(jane)! // instance for transaction\r\n jane.age = jane.age + 1\r\n transaction.commit {\r\n let jane = CoreStore.fetchExisting(jane)! // instance for DataStack\r\n print(jane.age)\r\n }\r\n}\r\n```\r\n`fetchExisting(...)` also works with multiple `NSManagedObject`s or with `NSManagedObjectID`s:\r\n```swift\r\nvar peopleIDs: [NSManagedObjectID] = // ...\r\n\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jane = transaction.fetchOne(\r\n From(MyPersonEntity),\r\n Where(\"name\", isEqualTo: \"Jane Smith\")\r\n )\r\n jane.friends = NSSet(array: transaction.fetchExisting(peopleIDs)!)\r\n // ...\r\n}\r\n```\r\n\r\n\r\n## Importing data\r\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. Say you have a JSON dictionary, you may be extracting values as such:\r\n```swift\r\nlet json: [String: AnyObject] = // ...\r\nperson.name = json[\"name\"] as? NSString\r\nperson.age = json[\"age\"] as? NSNumber\r\n// ...\r\n```\r\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:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let json: [String: AnyObject] = // ...\r\n try! transaction.importObject(\r\n Into(MyPersonEntity),\r\n source: json\r\n )\r\n transaction.commit()\r\n}\r\n```\r\nTo support data import for an entity, implement either `ImportableObject` or `ImportableUniqueObject` on the `NSManagedObject` subclass:\r\n- `ImportableObject`: Use this protocol if the object have no inherent uniqueness and new objects should always be added when calling `importObject(...)`.\r\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(...)`.\r\n\r\nBoth protocols require implementers to specify an `ImportSource` which can be set to any type that the object can extract data from:\r\n```swift\r\ntypealias ImportSource = NSDictionary\r\n```\r\n```swift\r\ntypealias ImportSource = [String: AnyObject]\r\n```\r\n```swift\r\ntypealias ImportSource = NSData\r\n```\r\nYou can even use external types from popular 3rd-party JSON libraries ([SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)'s `JSON` type is a personal favorite), or just simple tuples or primitives.\r\n\r\n#### `ImportableObject`\r\n`ImportableObject` is a very simple protocol:\r\n```swift\r\npublic protocol ImportableObject: class {\r\n typealias ImportSource\r\n static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool\r\n func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws\r\n}\r\n```\r\nFirst, set `ImportSource` to the expected type of the data source:\r\n```swift\r\ntypealias ImportSource = [String: AnyObject]\r\n```\r\nThis lets us call `importObject(_:source:)` with any `[String: AnyObject]` type as the argument to `source`:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let json: [String: AnyObject] = // ...\r\n try! transaction.importObject(\r\n Into(MyPersonEntity),\r\n source: json\r\n )\r\n // ...\r\n}\r\n```\r\nThe actual extraction and assignment of values should be implemented in the `didInsertFromImportSource(...)` method of the `ImportableObject` protocol:\r\n```swift\r\nfunc didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws {\r\n self.name = source[\"name\"] as? NSString\r\n self.age = source[\"age\"] as? NSNumber\r\n // ...\r\n}\r\n```\r\nTransactions also let you import multiple objects at once using the `importObjects(_:sourceArray:)` method:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jsonArray: [[String: AnyObject]] = // ...\r\n try! transaction.importObjects(\r\n Into(MyPersonEntity),\r\n sourceArray: jsonArray\r\n )\r\n // ...\r\n}\r\n```\r\nDoing so tells the transaction to iterate through the array of import sources and calls `shouldInsertFromImportSource(...)` on the `ImportableObject` to determine which instances should be created. You can do validations and return `false` from `shouldInsertFromImportSource(...)` if you want to skip importing from a source and continue on with the other sources in the array.\r\n\r\nIf on the other hand, your validation in one of the sources failed in such a manner that all other sources should also be cancelled, you can `throw` from within `didInsertFromImportSource(...)`:\r\n```swift\r\nfunc didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws {\r\n self.name = source[\"name\"] as? NSString\r\n self.age = source[\"age\"] as? NSNumber\r\n // ...\r\n if self.name == nil {\r\n throw Errors.InvalidNameError\r\n }\r\n}\r\n```\r\nDoing so can let you abandon an invalid transaction immediately:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jsonArray: [[String: AnyObject]] = // ...\r\n do {\r\n try transaction.importObjects(\r\n Into(MyPersonEntity),\r\n sourceArray: jsonArray\r\n )\r\n }\r\n catch {\r\n return // Woops, don't save\r\n }\r\n transaction.commit {\r\n // ...\r\n }\r\n}\r\n```\r\n\r\n#### `ImportableUniqueObject`\r\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:\r\n```swift\r\npublic protocol ImportableUniqueObject: ImportableObject {\r\n typealias ImportSource\r\n typealias UniqueIDType: NSObject\r\n\r\n static var uniqueIDKeyPath: String { get }\r\n var uniqueIDValue: UniqueIDType { get set }\r\n\r\n static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool\r\n static func shouldUpdateFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool\r\n static func uniqueIDFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws -> UniqueIDType?\r\n func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws\r\n func updateFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws\r\n}\r\n```\r\nNotice that it has the same insert methods as `ImportableObject`, with additional methods for updates and for specifying the unique ID:\r\n```swift\r\nclass var uniqueIDKeyPath: String {\r\n return \"personID\" \r\n}\r\nvar uniqueIDValue: NSNumber { \r\n get { return self.personID }\r\n set { self.personID = newValue }\r\n}\r\nclass func uniqueIDFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws -> NSNumber? {\r\n return source[\"id\"] as? NSNumber\r\n}\r\n```\r\nFor `ImportableUniqueObject`, the extraction and assignment of values should be implemented from the `updateFromImportSource(...)` method. The `didInsertFromImportSource(...)` by default calls `updateFromImportSource(...)`, but you can separate the implementation for inserts and updates if needed.\r\n\r\nYou can then create/update an object by calling a transaction's `importUniqueObject(...)` method:\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let json: [String: AnyObject] = // ...\r\n try! transaction.importUniqueObject(\r\n Into(MyPersonEntity),\r\n source: json\r\n )\r\n // ...\r\n}\r\n```\r\nor multiple objects at once with the `importUniqueObjects(...)` method:\r\n\r\n```swift\r\nCoreStore.beginAsynchronous { (transaction) -> Void in\r\n let jsonArray: [[String: AnyObject]] = // ...\r\n try! transaction.importObjects(\r\n Into(MyPersonEntity),\r\n sourceArray: jsonArray\r\n )\r\n // ...\r\n}\r\n```\r\nAs with `ImportableObject`, you can control wether to skip importing an object by implementing \r\n`shouldInsertFromImportSource(...)` and `shouldUpdateFromImportSource(...)`, or to cancel all objects by `throw`ing an error from the `uniqueIDFromImportSource(...)`, `didInsertFromImportSource(...)` or `updateFromImportSource(...)` methods.\r\n\r\n\r\n## Fetching and Querying\r\nBefore we dive in, be aware that CoreStore distinguishes between *fetching* and *querying*:\r\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:\r\n - results need to be `NSManagedObject` instances\r\n - unsaved objects should be included in the search (though fetches can be configured to exclude unsaved ones)\r\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:\r\n - you need to compute aggregate functions (see below for a list of supported functions)\r\n - results can be raw values like `NSString`s, `NSNumber`s, `Int`s, `NSDate`s, an `NSDictionary` of key-values, etc.\r\n - only values for specified attribute keys need to be included in the results\r\n - unsaved objects should be ignored\r\n\r\n#### `From` clause\r\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:\r\n```swift\r\nlet people = CoreStore.fetchAll(From(MyPersonEntity))\r\n// CoreStore.fetchAll(From<MyPersonEntity>()) works as well\r\n```\r\n`people` in the example above will be of type `[MyPersonEntity]`. The `From(MyPersonEntity)` clause indicates a fetch to all persistent stores that `MyPersonEntity` belong to.\r\n\r\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:\r\n```swift\r\nlet people = CoreStore.fetchAll(From<MyPersonEntity>(\"Config1\")) // ignore objects in persistent stores other than the \"Config1\" configuration\r\n```\r\nor if the persistent store is the auto-generated \"Default\" configuration, specify `nil`:\r\n```swift\r\nlet person = CoreStore.fetchAll(From<MyPersonEntity>(nil))\r\n```\r\nNow we know how to use a `From` clause, let's move on to fetching and querying.\r\n\r\n### Fetching\r\n\r\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.\r\n\r\n- `fetchAll(...)` - returns an array of all objects that match the criteria.\r\n- `fetchOne(...)` - returns the first object that match the criteria.\r\n- `fetchCount(...)` - returns the number of objects that match the criteria.\r\n- `fetchObjectIDs(...)` - returns an array of `NSManagedObjectID`s for all objects that match the criteria.\r\n- `fetchObjectID(...)` - returns the `NSManagedObjectID`s for the first objects that match the criteria.\r\n\r\nEach method's purpose is straightforward, but we need to understand how to set the clauses for the fetch.\r\n\r\n#### `Where` clause\r\n\r\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):\r\n```swift\r\nvar people = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(\"%K > %d\", \"age\", 30) // string format initializer\r\n)\r\npeople = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(true) // boolean initializer\r\n)\r\n```\r\nIf you do have an existing `NSPredicate` instance already, you can pass that to `Where` as well:\r\n```swift\r\nlet predicate = NSPredicate(...)\r\nvar people = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(predicate) // predicate initializer\r\n)\r\n```\r\n`Where` clauses also implement the `&&`, `||`, and `!` logic operators, so you can provide logical conditions without writing too much `AND`, `OR`, and `NOT` strings:\r\n```swift\r\nvar people = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(\"age > %d\", 30) && Where(\"gender == %@\", \"M\")\r\n)\r\n```\r\nIf you do not provide a `Where` clause, all objects that belong to the specified `From` will be returned.\r\n\r\n#### `OrderBy` clause\r\n\r\nThe `OrderBy` clause is CoreStore's `NSSortDescriptor` wrapper. Use it to specify attribute keys in which to sort the fetch (or query) results with.\r\n```swift\r\nvar mostValuablePeople = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n OrderBy(.Descending(\"rating\"), .Ascending(\"surname\"))\r\n)\r\n```\r\nAs seen above, `OrderBy` accepts a list of `SortKey` enumeration values, which can be either `.Ascending` or `.Descending`.\r\n\r\nYou can use the `+` and `+=` operator to append `OrderBy`s together. This is useful when sorting conditionally:\r\n```swift\r\nvar orderBy = OrderBy(.Descending(\"rating\"))\r\nif sortFromYoungest {\r\n orderBy += OrderBy(.Ascending(\"age\"))\r\n}\r\nvar mostValuablePeople = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n orderBy\r\n)\r\n```\r\n\r\n#### `Tweak` clause\r\n\r\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:\r\n```swift\r\nvar people = CoreStore.fetchAll(\r\n From(MyPersonEntity),\r\n Where(\"age > %d\", 30),\r\n OrderBy(.Ascending(\"surname\")),\r\n Tweak { (fetchRequest) -> Void in\r\n fetchRequest.includesPendingChanges = false\r\n fetchRequest.returnsObjectsAsFaults = false\r\n fetchRequest.includesSubentities = false\r\n }\r\n)\r\n```\r\nThe clauses are evaluated the order they appear in the fetch/query, so you typically need to set `Tweak` as the last clause.\r\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.\r\n\r\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!\r\n\r\n### Querying\r\n\r\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:\r\n\r\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.\r\n- `queryAttributes(...)` - returns an array of dictionaries containing attribute keys with their corresponding values.\r\n\r\nBoth methods above accept the same parameters: a required `From` clause, a required `Select<T>` clause, and an optional series of `Where`, `OrderBy`, `GroupBy`, and/or `Tweak` clauses.\r\n\r\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<T>` and `GroupBy` clauses.\r\n\r\n#### `Select<T>` clause\r\n\r\nThe `Select<T>` clause specifies the target attribute/aggregate key, as well as the expected return type: \r\n```swift\r\nlet johnsAge = CoreStore.queryValue(\r\n From(MyPersonEntity),\r\n Select<Int>(\"age\"),\r\n Where(\"name == %@\", \"John Smith\")\r\n)\r\n```\r\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<Int>` generic type. For `queryValue(...)`, the following are allowed as the return type (and therefore as the generic type for `Select<T>`):\r\n- `Bool`\r\n- `Int8`\r\n- `Int16`\r\n- `Int32`\r\n- `Int64`\r\n- `Double`\r\n- `Float`\r\n- `String`\r\n- `NSNumber`\r\n- `NSString`\r\n- `NSDecimalNumber`\r\n- `NSDate`\r\n- `NSData`\r\n- `NSManagedObjectID`\r\n- `NSString`\r\n\r\nFor `queryAttributes(...)`, only `NSDictionary` is valid for `Select`, thus you are allowed to omit the generic type:\r\n```swift\r\nlet allAges = CoreStore.queryAttributes(\r\n From(MyPersonEntity),\r\n Select(\"age\")\r\n)\r\n```\r\n\r\nIf you only need a value for a particular attribute, you can just specify the key name (like we did with `Select<Int>(\"age\")`), but several aggregate functions can also be used as parameter to `Select`:\r\n- `.Average(...)`\r\n- `.Count(...)`\r\n- `.Maximum(...)`\r\n- `.Minimum(...)`\r\n- `.Sum(...)`\r\n\r\n```swift\r\nlet oldestAge = CoreStore.queryValue(\r\n From(MyPersonEntity),\r\n Select<Int>(.Maximum(\"age\"))\r\n)\r\n```\r\n\r\nFor `queryAttributes(...)` which returns an array of dictionaries, you can specify multiple attributes/aggregates to `Select`:\r\n```swift\r\nlet personJSON = CoreStore.queryAttributes(\r\n From(MyPersonEntity),\r\n Select(\"name\", \"age\")\r\n)\r\n```\r\n`personJSON` will then have the value:\r\n```swift\r\n[\r\n [\r\n \"name\": \"John Smith\",\r\n \"age\": 30\r\n ],\r\n [\r\n \"name\": \"Jane Doe\",\r\n \"age\": 22\r\n ]\r\n]\r\n```\r\nYou can also include an aggregate as well:\r\n```swift\r\nlet personJSON = CoreStore.queryAttributes(\r\n From(MyPersonEntity),\r\n Select(\"name\", .Count(\"friends\"))\r\n)\r\n```\r\nwhich returns:\r\n```swift\r\n[\r\n [\r\n \"name\": \"John Smith\",\r\n \"count(friends)\": 42\r\n ],\r\n [\r\n \"name\": \"Jane Doe\",\r\n \"count(friends)\": 231\r\n ]\r\n]\r\n```\r\nThe `\"count(friends)\"` key name was automatically used by CoreStore, but you can specify your own key alias if you need:\r\n```swift\r\nlet personJSON = CoreStore.queryAttributes(\r\n From(MyPersonEntity),\r\n Select(\"name\", .Count(\"friends\", As: \"friendsCount\"))\r\n)\r\n```\r\nwhich now returns:\r\n```swift\r\n[\r\n [\r\n \"name\": \"John Smith\",\r\n \"friendsCount\": 42\r\n ],\r\n [\r\n \"name\": \"Jane Doe\",\r\n \"friendsCount\": 231\r\n ]\r\n]\r\n```\r\n\r\n#### `GroupBy` clause\r\n\r\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.\r\n```swift\r\nlet personJSON = CoreStore.queryAttributes(\r\n From(MyPersonEntity),\r\n Select(\"age\", .Count(\"age\", As: \"count\")),\r\n GroupBy(\"age\")\r\n)\r\n```\r\nthis returns dictionaries that shows the count for each `\"age\"`:\r\n```swift\r\n[\r\n [\r\n \"age\": 42,\r\n \"count\": 1\r\n ],\r\n [\r\n \"age\": 22,\r\n \"count\": 1\r\n ]\r\n]\r\n```\r\n\r\n## Logging and error handling\r\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.\r\n```swift\r\nfinal class MyLogger: CoreStoreLogger {\r\n func log(#level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {\r\n // pass to your logger\r\n }\r\n \r\n func handleError(#error: NSError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {\r\n // pass to your logger\r\n }\r\n \r\n func assert(@autoclosure condition: () -> Bool, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {\r\n // pass to your logger\r\n }\r\n}\r\n```\r\nThen pass an instance of this class to `CoreStore`:\r\n```swift\r\nCoreStore.logger = MyLogger()\r\n```\r\nDoing so channels all logging calls to your logger.\r\n\r\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.\r\n\r\n## Observing changes and notifications (unavailable on OSX)\r\nCoreStore provides type-safe wrappers for observing managed objects:\r\n\r\n- `ObjectMonitor`: use to monitor changes to a single `NSManagedObject` instance (instead of Key-Value Observing)\r\n- `ListMonitor`: use to monitor changes to a list of `NSManagedObject` instances (instead of `NSFetchedResultsController`)\r\n\r\n### Observe a single object\r\n\r\nTo observe an object, implement the `ObjectObserver` protocol and specify the `EntityType`:\r\n```swift\r\nclass MyViewController: UIViewController, ObjectObserver {\r\n func objectMonitor(monitor: ObjectMonitor<MyPersonEntity>, willUpdateObject object: MyPersonEntity) {\r\n // ...\r\n }\r\n \r\n func objectMonitor(monitor: ObjectMonitor<MyPersonEntity>, didUpdateObject object: MyPersonEntity, changedPersistentKeys: Set<KeyPath>) {\r\n // ...\r\n }\r\n \r\n func objectMonitor(monitor: ObjectMonitor<MyPersonEntity>, didDeleteObject object: MyPersonEntity) {\r\n // ...\r\n }\r\n}\r\n```\r\nWe then need to keep a `ObjectMonitor` instance and register our `ObjectObserver` as an observer:\r\n```swift\r\nlet person: MyPersonEntity = // ...\r\nself.monitor = CoreStore.monitorObject(person)\r\nself.monitor.addObserver(self)\r\n```\r\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.\r\n\r\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. \r\n\r\nWhile `ObjectMonitor` exposes `removeObserver(...)` as well, it only stores `weak` references of the observers and will safely unregister deallocated observers. \r\n\r\n### Observe a list of objects\r\nTo observe a list of objects, implement one of the `ListObserver` protocols and specify the `EntityType`:\r\n```swift\r\nclass MyViewController: UIViewController, ListObserver {\r\n func listMonitorWillChange(monitor: ListMonitor<MyPersonEntity>) {\r\n // ...\r\n }\r\n \r\n func listMonitorDidChange(monitor: ListMonitor<MyPersonEntity>) {\r\n // ...\r\n }\r\n}\r\n```\r\nIncluding `ListObserver`, there are 3 observer protocols you can implement depending on how detailed you need to handle a change notification:\r\n- `ListObserver`: lets you handle these callback methods:\r\n```swift\r\n func listMonitorWillChange(monitor: ListMonitor<MyPersonEntity>)\r\n\r\n func listMonitorDidChange(monitor: ListMonitor<MyPersonEntity>)\r\n```\r\n- `ListObjectObserver`: in addition to `ListObserver` methods, also lets you handle object inserts, updates, and deletes:\r\n```swift\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didInsertObject object: MyPersonEntity, toIndexPath indexPath: NSIndexPath)\r\n\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didDeleteObject object: MyPersonEntity, fromIndexPath indexPath: NSIndexPath)\r\n\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didUpdateObject object: MyPersonEntity, atIndexPath indexPath: NSIndexPath)\r\n\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didMoveObject object: MyPersonEntity, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath)\r\n```\r\n- `ListSectionObserver`: in addition to `ListObjectObserver` methods, also lets you handle section inserts and deletes:\r\n```swift\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)\r\n\r\n func listMonitor(monitor: ListMonitor<MyPersonEntity>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)\r\n```\r\n\r\nWe then need to create a `ListMonitor` instance and register our `ListObserver` as an observer:\r\n```swift\r\nself.monitor = CoreStore.monitorList(\r\n From(MyPersonEntity),\r\n Where(\"age > 30\"),\r\n OrderBy(.Ascending(\"name\")),\r\n Tweak { (fetchRequest) -> Void in\r\n fetchRequest.fetchBatchSize = 20\r\n }\r\n)\r\nself.monitor.addObserver(self)\r\n```\r\nSimilar to `ObjectMonitor`, a `ListMonitor` can also have multiple `ListObserver`s registered to a single `ListMonitor`.\r\n\r\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.\r\n\r\nA `ListMonitor` created from `monitorList(...)` will maintain a single-section list. You can therefore access its contents with just an index:\r\n```swift\r\nlet firstPerson = self.monitor[0]\r\n```\r\n\r\nIf the list needs to be grouped into sections, create the `ListMonitor` instance with the `monitorSectionedList(...)` method and a `SectionBy` clause:\r\n```swift\r\nself.monitor = CoreStore.monitorSectionedList(\r\n From(MyPersonEntity),\r\n SectionBy(\"age\"),\r\n Where(\"gender\", isEqualTo: \"M\"),\r\n OrderBy(.Ascending(\"age\"), .Ascending(\"name\")),\r\n Tweak { (fetchRequest) -> Void in\r\n fetchRequest.fetchBatchSize = 20\r\n }\r\n)\r\n```\r\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`.)\r\n\r\nThe `SectionBy` clause can also be passed a closure to transform the section name into a displayable string:\r\n```swift\r\nself.monitor = CoreStore.monitorSectionedList(\r\n From(MyPersonEntity),\r\n SectionBy(\"age\") { (sectionName) -> String? in\r\n \"\\(sectionName) years old\"\r\n },\r\n OrderBy(.Ascending(\"age\"), .Ascending(\"name\"))\r\n)\r\n```\r\nThis is useful when implementing a `UITableViewDelegate`'s section header:\r\n```swift\r\nfunc tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {\r\n let sectionInfo = self.monitor.sectionInfoAtIndex(section)\r\n // sectionInfo is an NSFetchedResultsSectionInfo instance\r\n return sectionInfo.name\r\n}\r\n```\r\n\r\nTo access the objects of a sectioned list, use an `NSIndexPath` or a tuple:\r\n```swift\r\nlet indexPath = NSIndexPath(forRow: 2, inSection: 1)\r\nlet person1 = self.monitor[indexPath]\r\nlet person2 = self.monitor[1, 2]\r\n// person1 and person2 are the same object\r\n```\r\n\r\n\r\n# Roadmap\r\n- Support iCloud stores\r\n- CoreSpotlight auto-indexing (experimental)\r\n\r\n\r\n# Installation\r\n- Requires:\r\n - iOS 8 SDK and above\r\n - Swift 2.1 (Xcode 7.2)\r\n- Dependencies:\r\n - [GCDKit](https://github.com/JohnEstropia/GCDKit)\r\n\r\n### Install with CocoaPods\r\n```\r\npod 'CoreStore'\r\n```\r\nThis installs CoreStore as a framework. Declare `import CoreStore` in your swift file to use the library.\r\n\r\n### Install with Carthage\r\nIn your `Cartfile`, add\r\n```\r\ngithub \"JohnEstropia/CoreStore\" >= 1.4.4\r\ngithub \"JohnEstropia/GCDKit\" >= 1.1.7\r\n```\r\nand run \r\n```\r\ncarthage update\r\n```\r\n\r\n### Install as Git Submodule\r\n```\r\ngit submodule add https://github.com/JohnEstropia/CoreStore.git <destination directory>\r\n```\r\nDrag and drop **CoreStore.xcodeproj** to your project.\r\n\r\n#### To install as a framework:\r\nDrag and drop **CoreStore.xcodeproj** to your project.\r\n\r\n#### To include directly in your app module:\r\nAdd all *.swift* files to your project.\r\n\r\n\r\n\r\n# Changesets\r\n### Upgrading from v0.2.0 to 1.0.0\r\n- Renamed some classes/protocols to shorter, more relevant, easier to remember names:\r\n- `ManagedObjectController` to `ObjectMonitor`\r\n- `ManagedObjectObserver` to `ObjectObserver`\r\n- `ManagedObjectListController` to `ListMonitor`\r\n- `ManagedObjectListChangeObserver` to `ListObserver`\r\n- `ManagedObjectListObjectObserver` to `ListObjectObserver`\r\n- `ManagedObjectListSectionObserver` to `ListSectionObserver`\r\n- `SectionedBy` to `SectionBy` (match tense with `OrderBy` and `GroupBy`)\r\nThe protocols above had their methods renamed as well, to retain the natural language semantics.\r\n- Several methods now `throw` errors insted of returning a result `enum`.\r\n- New migration utilities! (README still pending) Check out *DataStack+Migration.swift* and *CoreStore+Migration.swift* for the new methods, as well as *DataStack.swift* for its new initializer.\r\n\r\n\r\n\r\n# Contributions\r\nWhile CoreStore's design is pretty solid and the unit test and demo app work well, CoreStore is pretty much still in its early stage. With more exposure to production code usage and criticisms from the developer community, CoreStore hopes to mature as well.\r\nPlease feel free to report any issues, suggestions, or criticisms!\r\n日本語で連絡していただいても構いません!\r\n\r\n## License\r\nCoreStore is released under an MIT license. See the LICENSE file for more information\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."} |