Applications open for January and September 2018 - Apply Now

X

In this section of the tutorial we will create CoreData helper methods that will make it easier to integrate CoreData into our project in the next section. The CoreData helper methods will allow us to easily add new notes, update existing notes, delete old notes, and retrieve existing notes.

Delete your old Note.swift Class

In order to get CoreData working with your new class, you'll first need to delete the note class that you made earlier. If you don't, Xcode will get confused, but don't worry, because CoreData will generate a new class for you!

Control-Click or Right-Click on Note.swift, and click Delete.

Add Note entity in the data model

Now we need to show CoreData what kind of object we want it to make. We'll do this in the MakeSchoolNotes.xcdatamodeld file.

Click MakeSchoolNotes.xcdatamodeld and you will see your data model for CoreData. Follow the following steps to create an entity in CoreData

  1. On the bottom left, you will see "Add Entity". Click it.
  2. On the top left, you will see the entity you just created called "Entity". Double click "Entity" to change the name to "Note"
  3. On the right side, you will see a section called "Attributes". You will need to create 3 attributes for Note. Click the "+" sign 3 times and add the following attributes.

    title with type String
    
    content with type String
    
    modificationTime with type Date
  4. On the right side, change the class from the default NSManagedObject to the Note class you defined.

  5. On the right side, change the Module field to Current Product Module.

Correct settings for entity

Creating CoreData Helper Methods

Create a new file called CoreDataHelper.swift in the Helpers group.

In CoreDataHelper.swift we will define static methods that we can call to add, update, retrieve, and delete notes.

First we will want to import CoreData and define a CoreDataHelper class as follows:

import CoreData
import UIKit

class CoreDataHelper {
    static let appDelegate = UIApplication.shared.delegate as! AppDelegate
    static let persistentContainer = appDelegate.persistentContainer
    static let managedContext = persistentContainer.viewContext
    //static methods will go here
}

Static Methods

Static methods are methods that can be called directly on the class, without having to instantiate an instance of the class first. For example, if we add a static method called doSomething() to the CoreDataHelper class, we can call it like this:

CoreDataHelper.doSomething()

If doSomething() were not static, calling it would look like more like this:

let CoreDataHelper = CoreDataHelper()
CoreDataHelper.doSomething()

To declare a static method is very easy, just add the static keyword to the front of the declaration. Here's how our CoreDataHelper would look with a static doSomething() method:

class CoreDataHelper {
    static func doSomething() {

    }
}

Create Note

We want to define a static method that creates a note object, and then returns it.

Try it on your own and then compare with the solution below. It's okay to look back to the last section to see how it's done.

static func newNote() -> Note {
    let note = NSEntityDescription.insertNewObject(forEntityName: "Note", into: managedContext) as! Note
    return note
}

Save Note

We want to define a static method that saves that note to the default CoreData.

Try it on your own first!.

static func saveNote() {
    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save \(error)")
    }
}

Delete Note

We want to define a static method that accepts a Note object as its one parameter and then deletes that note from the default CoreData.

Try it on your own first!

static func delete(note: Note) {
    managedContext.delete(note)
    saveNote()
}

Retrieve Notes

We want to define a static method that retrieves all notes from the default CoreData. Unlike the other helper methods, this one should return a [Note] object.

Try it on your own, don't be afraid to refer back to the previous section!

static func retrieveNotes() -> [Note] {
    let fetchRequest = NSFetchRequest<Note>(entityName: "Note")
    do {
        let results = try managedContext.fetch(fetchRequest)
        return results
    } catch let error as NSError {
        print("Could not fetch \(error)")
    }
    return []
}

Wrapping Up

We now have all the helper methods we will need to integrate CoreData into Make School Notes! In the next section let's (finally) add persistence to our Make School Notes app!

On this page, you should have:

  1. Learned what a static method is, and how to make one.
  2. Created the CoreDataHelper class.
  3. Implemented three different static helper methods within the CoreDataHelper class, ones to save, delete, and retrieve notes from CoreData.

Feedback

If you have feedback on this tutorial or find any mistakes, please open issues on the GitHub Repository or comment below.

Summer academy

An iOS Development Summer Course

Design, code and launch your own app. Locations in San Francisco and Asia

Find your location

Product College

A computer science college

Graduate into a successful career as a founder or software engineer.

Learn more