A container that encapsulates the Core Data stack in your application.


NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model (NSManagedObjectModel), persistent store coordinator (NSPersistentStoreCoordinator), and the managed object context (NSManagedObjectContext).


Creating a Container

init(name: String)

Initializes a persistent container with the given name.

init(name: String, managedObjectModel: NSManagedObjectModel)

Initializes a persistent container with the given name and model.

Configuring a Container

var persistentStoreDescriptions: [NSPersistentStoreDescription]

The persistent store descriptions used to create the persistent stores referenced by this persistent container.

func loadPersistentStores(completionHandler: (NSPersistentStoreDescription, Error?) -> Void)

Instructs the persistent container to load the persistent stores.

var managedObjectModel: NSManagedObjectModel

The model associated with this persistent container. (read-only)

var name: String

The name of this persistent container. (read-only)

var persistentStoreCoordinator: NSPersistentStoreCoordinator

The persistent store coordinator associated with this persistent container. (read-only)

Accessing the Context(s)

func newBackgroundContext()

Creates a private managed object context.

func performBackgroundTask((NSManagedObjectContext) -> Void)

Causes the persistent container to execute the block against a new private queue context.

var viewContext: NSManagedObjectContext

The managed object context associated with the main queue. (read-only)

Configuring the Store Location

class func defaultDirectoryURL()

Creates the default directory for the persistent stores on the current platform.


Inherits From

Conforms To

See Also

Core Data Stack

class NSManagedObjectContext

An object representing a single object space or scratch pad that you use to fetch, create, and save managed objects.

class NSPersistentStoreCoordinator

A coordinator that associates persistent stores with a model (or a configuration of a model) and that mediates between the persistent stores and the managed object contexts.

class NSManagedObjectModel

An object that describes a schema—a collection of entities (data models) that you use in your application.