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


class NSPersistentContainer : NSObject


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() -> NSManagedObjectContext

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() -> URL

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


Inherits From

Conforms To

See Also

Stack Fundamentals

class NSManagedObjectModel

A programmatic representation of the .xcdatamodeld file describing your objects.

class NSManagedObjectContext

An object space that you use to manipulate and track changes to managed objects.

class NSPersistentStoreCoordinator

A coordinator that uses the model to help contexts and persistent stores communicate.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software