Core Data Cheat Sheet for Swift iOS Developers

Updated on July 27, 2016 – Additional Cheats

Having trouble recalling how to perform basic Core Data operations? This cheat sheet is a handy reference to keep you productive with Core Data and Swift!

The code snippets below are here to help jog your memory when it’s been a while since you’ve worked in Core Data. They could also be helpful for newcomers to iOS development, Core Data, and Swift.

One assumption I’m making in this post is that you’ve created NSManagedObject subclasses for your entities to make them easier to work with in a type-safe way. If you need help getting started with that, I’ve written a walk-through to guide you through that process.

Querying

Fetch all entities

1// Assuming type has a reference to managed object context
2
3let fetchRequest = NSFetchRequest(entityName: "MyEntity")
4do {
5    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
6    // Do something with fetchedEntities
7} catch {
8    // Do something in response to error condition
9}

Fetch maximum of N entities

 1// Assuming type has a reference to managed object context
 2
 3let fetchRequest = NSFetchRequest(entityName: "MyEntity")
 4fetchRequest.fetchLimit = 10
 5do {
 6    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
 7    // Do something with fetchedEntities
 8} catch {
 9    // Do something in response to error condition
10}   

Insert a new entity

 1// Assuming encapsulating Type has a reference to managed object context
 2
 3let newEntity = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: self.managedObjectContext) as! MyEntity
 4// Set properties
 5
 6do {
 7    try self.managedObjectContext.save()
 8} catch {
 9    // Do something in response to error condition
10}

Update a single entity

 1// Assuming type has a reference to managed object context
 2
 3// Assuming that a specific NSManagedObject's objectID property is accessible
 4// Alternatively, could supply a predicate expression that's precise enough
 5// to select only a _single_ entity
 6let predicate = NSPredicate(format: "objectID == %@", objectIDFromNSManagedObject)
 7
 8let fetchRequest = NSFetchRequest(entityName: "MyEntity")
 9fetchRequest.predicate = predicate
10
11do {
12    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
13    fetchedEntities.first?.FirstPropertyToUpdate = NewValue
14    fetchedEntities.first?.SecondPropertyToUpdate = NewValue
15    // ... Update additional properties with new values
16} catch {
17    // Do something in response to error condition
18}
19
20do {
21    try self.managedObjectContext.save()
22} catch {
23    // Do something in response to error condition
24}

Update multiple-entities

 1// Assuming type has a reference to managed object context
 2
 3let predicate = NSPredicate(format: "MyEntityAttribute == %@", "Matching Value")
 4
 5let fetchRequest = NSFetchRequest(entityName: "MyEntity")
 6fetchRequest.predicate = predicate
 7
 8do {
 9    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
10    
11    for entity in fetchedEntities {
12        entity.FirstPropertyToUpdate = NewValue
13        entity.SecondPropertyToUpdate = NewValue
14        // ... Update additional properties with new values
15    }
16} catch {
17    // Do something in response to error condition
18}
19
20do {
21    try self.managedObjectContext.save()
22} catch {
23    // Do something in response to error condition
24}

Delete a single entity

 1// Assuming type has a reference to managed object context
 2
 3// Assuming that a specific NSManagedObject's objectID property is accessible
 4// Alternatively, could supply a predicate expression that's precise enough
 5// to select only a _single_ entity
 6let predicate = NSPredicate(format: "objectID == %@", objectIDFromNSManagedObject)
 7
 8let fetchRequest = NSFetchRequest(entityName: "MyEntity")
 9fetchRequest.predicate = predicate
10
11do {
12    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
13    if let entityToDelete = fetchedEntities.first {
14        self.managedObjectContext.deleteObject(entityToDelete)
15    }
16} catch {
17    // Do something in response to error condition
18}
19
20do {
21    try self.managedObjectContext.save()
22} catch {
23    // Do something in response to error condition
24}

Delete multiple-entities

 1// Assuming type has a reference to managed object context
 2
 3let predicate = NSPredicate(format: "MyEntityAttribute == %@", "Matching Value")
 4
 5let fetchRequest = NSFetchRequest(entityName: "MyEntity")
 6fetchRequest.predicate = predicate
 7
 8do {
 9    let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [MyEntity]
10    
11    for entity in fetchedEntities {
12        self.managedObjectContext.deleteObject(entity)
13    }
14} catch {
15    // Do something in response to error condition
16}
17
18do {
19    try self.managedObjectContext.save()
20} catch {
21    // Do something in response to error condition
22}

Migrate Core Data Model with Automatic Migrations

1let model = // set up model
2
3let pscOptions = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]
4    
5let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
6try! psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: pscOptions)

comments powered by Disqus