Giter Club home page Giter Club logo

coredatastack's Introduction

BNR Core Data Stack

Carthage compatible Cocoapods Compatible GitHub license Build Status

The BNR Core Data Stack is a small framework, written in Swift, that makes it easy to quickly set up a multi-threading ready Core Data stack.

For more details on the design methodology see: Introducing the Big Nerd Ranch Core Data Stack

Minimum Requirements

  • iOS 8.0
  • Xcode 7.0
  • Swift 2.0

Installation

Add the following to your Cartfile:

github "BigNerdRanch/CoreDataStack"

Then run carthage update.

Follow the current instructions in Carthage's README for up to date installation instructions.

Add the following to your Podfile:

pod 'BNRCoreDataStack'

You will also need to make sure you're opting into using frameworks:

use_frameworks!

Then run pod install.

Usage

Constructing Your Stack

Import Framework

via: Carthage

import CoreDataStack

or via CocoaPods

import BNRCoreDataStack

Standard SQLite Backed

CoreDataStack.constructSQLiteStack(withModelName: "TestModel") { result in
	switch result {
	case .Success(let stack):
		self.myCoreDataStack = stack
		print("Success")
	case .Failure(let error):
		print(error)
	}
}

In-Memory Only

do {
	myCoreDataStack = try CoreDataStack.constructInMemoryStack(withModelName: "TestModel")
} catch {
	print(error)
}

Working with Managed Object Contexts

Private Persisting/Coordinator Connected Context

This is the root level context with a PrivateQueueConcurrencyType for asynchronous saving to the NSPersistentStore. Fetching, Inserting, Deleting or Updating managed objects should occur on a child of this context rather than directly.

myCoreDataStack.privateQueueContext

Main Queue / UI Layer Context

This is our MainQueueConcurrencyType context with its parent being the private persisting context. This context should be used for any main queue or UI related tasks. Examples include setting up an NSFetchedResultsController, performing quick fetches, making UI related updates like a bookmark or favoriting an object. Performing a save() call on this context will automatically trigger a save on its parent via NSNotification.

myCoreDataStack.mainQueueContext

Creating a Worker Context

Calling newBackgroundWorkerMOC() will vend us a PrivateQueueConcurrencyType child context of the main queue context. Useful for any longer running task, such as inserting or updating data from a web service. Calling save() on this managed object context will automatically trigger a save on its parent context via NSNotification.

let workerContext = myCoreDataStack.newBackgroundWorkerMOC()
workerContext.performBlock() {
    // fetch data from web-service
    // update local data
    workerContext.saveContext()
}

Large Import Operation Context

In most cases, offloading your longer running work to a background worker context will be sufficient in alleviating performance woes. If you find yourself inserting or updating thousands of objects then perhaps opting for a stand alone managed object context with a discrete persistent store like so would be the best option:

myCoreDataStack.newBatchOperationContext() { result in
    switch result {
    case .Success(let batchContext):
        // my big import operation
    case .Failure(let error):
        print(error)
    }
}

Resetting The Stack

At times it can be necessary to completely reset your Core Data store and remove the file from disk for example when a user logs out of your application. An NSSQLiteStoreType stack can be reset using the function resetSQLiteStore(resetCallback: CoreDataStackSQLiteResetCallback).

myCoreDataStack.resetSQLiteStore() { result in
    switch result {
    case .Success:
        // proceed with fresh Core Data Stack
    case .Failure(let error):
        print(error)
    }
}

Debugging Tips

To validate that you are honoring all of the threading rules it's common to add the following to a project scheme under Run > Arguments > Arguments Passed On Launch.

-com.apple.CoreData.ConcurrencyDebug 1

This will throw an exception if you happen to break a threading rule. For more on setting up Launch Arguments check out this article by NSHipster.

About

Big Nerd Ranch

  • We Develop custom apps for clients around the world.
  • We Teach immersive development bootcamps.
  • We Write best-selling Big Nerd Ranch Guides.

coredatastack's People

Contributors

alessandroorru avatar corysullivan avatar rcedwards avatar zwaldowski avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.