Using Coredata in your iOS app

Implementing CoreData in your iOS app and CRUD’ing data.

1. Adding Coredata + xcdatamodel

When creating a new project simply make sure to include CoreData storage. Xcode will handle setting up CoreData in your project and will create the xcdatamodel for you.

If you are adding CoreData to an existing project, in this case, simply create a new xcdatamodel file:

New File -> Data Model

Also add the following code to your AppDelegate.swift:

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "ExampleCoreDataProject")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

Also add self.saveContext() to the applicationWillTerminate(_ application: UIApplication) method. Don’t forget to change the title of the container "ExampleCoreDataProject" with the title of your iOS app If your app has a dash in the name, such as: some-app, the container name will need to be some_app.

2. Create an entity

Create an entity in your xcdatamodel class, implement a similar class in code, such as the snippet below. Note that the entityTitle is the title given to the entity in the xcdatamodel:

import Foundation

public struct SerializedToken: Equatable, Codable {

    static let entityTitle = "Token"
    
    var label: String
    var secret: Data
    var algorithm: String
    var digitAmount: Int
    var code: String
    var issuer: String
    
    init(label: String, secret: Data, algorithm: String, code: String, issuer: String, digitAmount: Int) {
        self.label = label
        self.issuer = issuer
        self.algorithm = algorithm
        self.digitAmount = digitAmount
        self.code = code
        self.secret = secret
    }
    
    init(from token: Token) {
        self.label = token.label
        self.issuer = token.issuer
        self.algorithm = token.algorithm.rawValue
        self.digitAmount = token.digitAmount
        self.code = String(token.code.toString())
        self.secret = token.secret
    }
}

3. Error handling (optional)

A small enum for error handling which can be applied to your CoreData methods to handle certain exceptions. Modify it accordingly to your criteria.

public enum CoreDataError: Swift.Error {
    case duplicateItem(String)
    case itemDoesNotExist
    case unknownError
}

4. CRUD

Implement the following pieces of code to CRUD coredata. Naturally you will need to modify them according to your models. In case you are wondering how to retrieve the NSManagedObjectContext, you can check here.

Create
import CoreData

public class func saveToken(_ serializedtoken: SerializedToken, using context: NSManagedObjectContext) throws {
        
    guard !itemAlreadyExists(serializedtoken, using: context) else {
        throw CoreDataError.duplicateItem(serializedtoken.label)
    }
    
    let entity = NSEntityDescription.entity(forEntityName: SerializedToken.entityTitle, in: context)
    let newToken = NSManagedObject(entity: entity!, insertInto: context)
    
    newToken.setValue(serializedtoken.label, forKey: "label")
    newToken.setValue(serializedtoken.issuer, forKey: "issuer")
    newToken.setValue(serializedtoken.algorithm, forKey: "algorithm")
    newToken.setValue(serializedtoken.code, forKey: "code")
    newToken.setValue(serializedtoken.secret, forKey: "secret")
    newToken.setValue(serializedtoken.digitAmount, forKey: "digitamount")
    
    try! context.save()
}

Also a method to see if an item already exists within storage by a self-defined predicate:

import CoreData

public class func itemAlreadyExists(_ token: SerializedToken, using context: NSManagedObjectContext) -> Bool {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: SerializedToken.entityTitle)
    request.predicate = NSPredicate(format: "secret = %@ AND label = %@ AND algorithm =%@", token.secret as CVarArg, token.label, token.algorithm)
    request.returnsObjectsAsFaults = false
    if let result = try? context.fetch(request) {
        let foundItems = result as! [NSManagedObject]
        return foundItems.count > 0
    } else {
        return false
    }
}
Reading
import CoreData

public class func getTokens(context: NSManagedObjectContext) throws -> [SerializedToken] {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: SerializedToken.entityTitle)
    request.returnsObjectsAsFaults = false
    
    let result = try! context.fetch(request)
    var tokenResult = [[SerializedToken]()
    for data in result as! [NSManagedObject] {
        tokenResult.append(SerializedToken(
                        label: data.value(forKey: "label") as! String,
                        secret: data.value(forKey: "secret") as! Data,
                        algorithm: data.value(forKey: "algorithm") as! String,
                        code: data.value(forKey: "code") as! String,
                        issuer: data.value(forKey: "issuer") as! String,
                        digitAmount: data.value(forKey: "digitamount") as! Int)
                        )
    }
    
    return tokenResult
}
Update
import CoreData

public class func updateToken(_ serializedToken: SerializedToken, with updatedToken:SerializedToken, using context: NSManagedObjectContext) throws {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: SerializedToken.entityTitle)
    fetchRequest.predicate = NSPredicate(format: "secret = %@ AND label = %@ AND algorithm =%@", serializedToken.secret as CVarArg, serializedToken.label, serializedToken.algorithm)
    fetchRequest.returnsObjectsAsFaults = false
    
    if let result = try? context.fetch(fetchRequest) {
        let foundItems = result as! [NSManagedObject]
        guard foundItems.count > 0 else {
            throw CoreDataError.itemDoesNotExist
        }
        
        let foundToken = foundItems[0]
        foundToken.setValue(updatedToken.label, forKey: "label")
        foundToken.setValue(updatedToken.issuer, forKey: "issuer")
        try! context.save()
    } else {
        throw CoreDataError.unknownError
    }
}
Delete
import CoreData

public class func removeToken(_ serializedToken: SerializedToken, using context: NSManagedObjectContext) throws {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: SerializedToken.entityTitle)
    
    fetchRequest.predicate = NSPredicate(format: "secret = %@ AND label = %@ AND algorithm =%@", serializedToken.secret as CVarArg, serializedToken.label, serializedToken.algorithm)
    fetchRequest.returnsObjectsAsFaults = false
    
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    try! context.execute(deleteRequest)
    
}
import CoreData

public class func removeAllTokens(using context: NSManagedObjectContext) throws {
    let request = NSBatchDeleteRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: SerializedToken.entityTitle))
    try! context.execute(request)
}