Latest 0.4.0
Homepage https://github.com/oreillymedia/flapjack
License MIT
Platforms ios 11.0, tvos 11.0, osx 10.13
Frameworks Foundation
Authors

Flapjack is an iOS/macOS/tvOS framework with 2 primary goals.

  1. Help you abstract your model-focused database persistence layer from the rest of your app
  2. Simplify the database layer’s API into an easy-to-use, easy-to-remember, full Swift one

It lets you skip the boilerplate commonly associated with database layers like Core Data and lets you introduce structured, sane data persistence in your app sooner, letting you spend more of your time creating the app you really want. We use it at O’Reilly Media for our iOS apps, and if you like what you see, perhaps you will too.

Getting started

CocoaPods

Flapjack will soon be available through CocoaPods. To install it for now, simply add the following line to your Podfile:

pod 'Flapjack', git: 'https://github.com/oreillymedia/flapjack.git', tag: '0.1.0'
# If you're using Core Data...
pod 'Flapjack/CoreData', git: 'https://github.com/oreillymedia/flapjack.git', tag: '0.1.0'
# If you're targeting iOS and want some helpers...
pod 'Flapjack/UIKit', git: 'https://github.com/oreillymedia/flapjack.git', tag: '0.1.0'

And run pod install at the command line.

Carthage

Make the following entry in your Cartfile:

github "oreillymedia/flapjack"

Then run carthage update. If this is your first time using Carthage in the project, you’ll need to go through some additional steps as explained over at Carthage. Carthage will build three frameworks: Flapjack, FlapjackCoreData, and FlapjackUIKit. You’ll need Flapjack as a base framework, and if you’re using it with Core Data and/or UIKit, you’ll want to bring in those frameworks as well (and reference those in your import statements where necessary).

Swift Package Manager

Support for Swift Package Manager is in its initial stage; the project does not build with support for Core Data or UIKit, since those frameworks are not packaged or available for Swift Package Manager (since SPM only builds for the host platform, UIKit is currently impossible to use as a dependency for FlapjackUIKit). In order to use Flapjack by itself, add the following as a dependency to the dependencies array in your Package.swift file:

.package(url: "https://github.com/oreillymedia/flapjack.git", .upToNextMajor(from: "0.1.0"))

Then you’ll specify Flapjack as a dependency of the target in which you wish to use it.

Usage

Full documentation is forthcoming, but here’s a good thorough run-through of what Flapjack has to offer.

In your iOS project (like perhaps in your UIApplicationDelegate), kick things off with the following code (if you’re using Core Data; support for more databases planned).

import Flapjack

// Create the DataAccess object, your main point-of-entry for persistence.
// You can also pass in `.sql(filename: "YourCoreDataStore.sql")`.
let dataAccess = CoreDataAccess(name: "YourCoreDataStore", type: .memory)

// Then tell the stack to configure itself.
dataAccess.prepareStack(asynchronously: true) { error in
    if let error = error {
        print(error.localizedDescription)
    }

    // Make sure you retain your `dataAccess` variable, and now you're all
    //   ready to go!
}

For your model objects to take part in the simplified API provided by Flapjack, you’ll need to make sure they conform to DataObject. For a class such as Pancake that has the fields identifier, flavor, and radius defined in a Core Data model, this would look like the following.

extension Pancake: DataObject {
    // The type of your primary key, if you have one of your own.
    public typealias PrimaryKeyType = String
    // The name of the entity as Core Data knows it.
    public static var representedName: String {
        return "Pancake"
    }
    // The key path to your model's primary key.
    public static var primaryKeyPath: String {
        return #keyPath(identifier)
    }
    // An array of sorting criteria.
    public static var defaultSorters: [SortDescriptor] {
        return [
            SortDescriptor(#keyPath(flavor), ascending: true, caseInsensitive: true),
            SortDescriptor(#keyPath(radius), ascending: false)
        ]
    }
}

Now you’re cookin’. Interacting with the data store is even easier.

// Get every pancake.
let pancakes = dataAccess.mainContext.objects(ofType: Pancake.self)
// Get just the chocolate chip ones.
let pancakes = dataAccess.mainContext.objects(ofType: Pancake.self, attributes: ["flavor": "Chocolate Chip"])
// Create your own.
let pancake = dataAccess.mainContext.create(Pancake.self, attributes: ["flavor": "Rhubarb"])
// Save your changes.
let error = context.persist()

Granted you don’t want to do expensive data operations on the main thread. Flapjack’s Core Data support follows best practices for such a thing:

dataAccess.performInBackground { [weak self] context in
    let pancake = context.create(Pancake.self, attributes: ["flavor": flavor, "radius": radius, "height": height])
    let error = context.persist()

    DispatchQueue.main.async {
        guard let `self` = self else {
            return
        }
        let foregroundPancake = self.dataAccess.mainContext.object(ofType: Pancake.self, objectID: pancake.objectID)
        completion(foregroundPancake, error)
    }
}

Sick of your database? There’s a function for that, too.

dataAccess.deleteDatabase(rebuild: true) { error in
    if let error = error {
        print(error.localizedDescription)
    }

    // It's almost as if it never happened.
}

Data sources

This wouldn’t be nearly as much fun if Flapjack didn’t provide a way to automatically listen for model changes. The DataSource and SingleDataSource protocols define a way to listen for changes on a collection of persisted objects or a single object, respectively. If you’re targeting Core Data, the two implementations of those protocols (CoreDataSource and CoreSingleDataSource) are powered by NSFetchResultsController and listening to .NSManagedObjectContextObjectsDidChange, respectively.

import Flapjack

let dataSourceFactory = CoreDataSourceFactory(dataAccess: dataAccess)
let queryAttributes = ["radius": 2.0, "flavor": "Chocolate Chip"]
let dataSource: CoreDataSource<Pancake> = dataSourceFactory.vendObjectsDataSource(attributes: queryAttributes, sectionProperty: "flavor", limit: 100)

// Prepare yourself for pancakes, but only chocolate chip ones bigger than a 2" radius, and no more than 100.
// This block fires every time the data source picks up an insert/change/deletion.
dataSource.onChange = { itemChanges, sectionChanges in
    // If you've added `Flapjack/UIKit` to your Podfile, you get helper extensions!
    self.tableView.performBatchUpdates(itemChanges, sectionChanges: sectionChanges)

    // Get a specific pancake:
    print("(String(describing: dataSource.object(at: IndexPath(item: 0, section: 0))))")
}

// Kick off a call to start listening (and immediately fire `.onChange` with all existing results).
dataSource.execute()

For a more complete example on how to use CoreDataSource, see AutomaticViewController.swift. To see the steps you’d have to go through to access stored data without it, see ManualViewController.swift.

Migrations

Support for "easier" Core Data migrations is currently evolving, but here’s what you can expect right now. Flapjack has a Migrator class that you can conform to, and it’s this object you’ll use to provide your DataAccess class with a way to migrate your data store. It’s a relatively sparse protocol right now, but if you look at the Core Data implementation of this object (CoreDataMigrator), you can see how this comes together. This is a pretty close adaptation of the way we handle migrations in our iOS apps at O’Reilly Media. Here’s what happens, step by step.

  • By conforming to DataAccessDelegate, you’ll be notified when the stack is ready for a Migrator.
  • In response to this delegate call, you’ll initialize and return a CoreDataMigrator by providing the storeURL and bundle where the data store file and compiled model can be found, respectively.
  • Then the DataAccess object should handle the rest, which is essentially a call to migrate().
  • Upon invocation of migrate(), a temporary folder is made to house any intermediary files.
  • Then your compiled data model is scanned for all available model versions, and then we also try and figure out which version is the current version, and then we build an iterative list of versions by which to migrate (support for supplying a custom list of versions to migrate is forthcoming).
  • Then, between each version, we either process a heavyweight migration (if an explicit mapping model is found) or a lightweight migration (if an implicit mapping model can be inferred).

Authors

License

Flapjack is available under the MIT license. See LICENSE file for more info.

Latest podspec

{
    "name": "Flapjack",
    "version": "0.4.0",
    "summary": "A Swift data persistence API with support for Core Data.",
    "description": "Flapjack is an iOS/macOS/tvOS framework with 2 primary goals.nn1. Help you abstract your model-focused database persistence layer from the restn   of your appn2. Simplify the database layer's API into an easy-to-use, easy-to-remember, fulln   Swift onennIt lets you skip the boilerplate commonly associated with database layers likenCore Data and lets you introduce structured, sane data persistence in your appnsooner, letting you spend more of your time creating the app you really want. Wenuse it at O'Reilly Media and Safari Books Online for our iOS apps, and if younlike what you see, perhaps you will too.",
    "homepage": "https://github.com/oreillymedia/flapjack",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "authors": {
        "Ben Kreeger": "[email protected]"
    },
    "source": {
        "git": "https://github.com/oreillymedia/flapjack.git",
        "tag": "0.4.0"
    },
    "platforms": {
        "ios": "11.0",
        "tvos": "11.0",
        "osx": "10.13"
    },
    "frameworks": "Foundation",
    "swift_versions": "5.0",
    "default_subspecs": "Core",
    "subspecs": [
        {
            "name": "Core",
            "frameworks": "CoreData",
            "source_files": "Flapjack/Core/**/*.swift"
        },
        {
            "name": "CoreData",
            "dependencies": {
                "Flapjack/Core": []
            },
            "frameworks": "CoreData",
            "source_files": "Flapjack/CoreData/**/*"
        },
        {
            "name": "UIKit",
            "dependencies": {
                "Flapjack/Core": []
            },
            "ios": {
                "frameworks": "UIKit",
                "source_files": "Flapjack/UIKit/**/*"
            }
        }
    ]
}

Pin It on Pinterest

Share This