Swift – 4 – Core Data – Part 3 Creating a Singleton Core Data & refactoring insert, update, delete operations

Hello guys  😀 . In part 2 we learned about basic core data concepts with insert, update and delete operations. Before starting unit testing for core data we have to loosely couple our code. It will eventually make our view controller class also light weight.  Download Part 2 code for Starter.

Please support us by comment, like and share our facebook page.

In this part we will separate the core data related business logic in a separate class. Final source code is at end of this tutorial.

Have a ☕ and start code –

Add a file in your project and name it “CoreDataManager”.

Copy below code and paste it to “CoreDataManager”.

Let’s understand what’s going on:  🙄

  1. We are creating a static let, so that sharedManager have same instance  and can not be changed.
  2. Using private keyword, so that this class can not be initialize mistakenly. If at some place you will try to initialize it again you will get compile time error.
  3.  Initializing NSPersistentContainer, thus initializing complete core data stack lazily. persistentContainer object will be initialized only when it is needed. I have already over detailed in part 1.
  4. Save context method will save our uncommitted changes in core data store. I have already over detailed in part 1.

As we have put core data related code in separate file CoreDataManager, we will remove all code related to core data from AppDelegate file. 

  1. Remove import CoreData
  2. Remove lazy var persistentContainer: NSPersistentContainer = {……………………}()
  3. change applicationWillTerminate as below:

Your AppDelegate file should look like this:

See how much slim AppDelegate file looking now  😎

Run your project and see errors  😡

We are getting these error because we changed our AppDelegate file and we have still not make changes in ViewController class.

Open ViewController class and search for

replace appDelegate.persistentContainer.viewContext with 

Build and run, it should work now.  😀

We are still getting some warning in ViewController, so we need to remove code related to appDelegate.

Search & Delete wherever you find below code

Build and run your code it should work fine now.

Now moving ahead we need to write insert, update, delete and fetch methods in CoreDataManager class. That is we are going to refactor ViewController class.


copy code from ViewController and paste it in CoreDataManagerClass.

We do not need tableView, people.append..blah blah code.

We will make minor changes in above code and below is the fixed version.

Now open ViewController class and change

as per below code:

See the beauty of code now. It’s very light weight. isn’t it  :mrgreen:

  1. We are calling insertPerson method of CoreDataManager class, it will return a optional person ❓  object.
  2. Before unwrapping it we must make sure it is not nil to be saved from run time crash. If it is not nil then only force unwrap it. You can also use optional binding to get unwrapped value.
  3. Add this object in table view data source array
  4. Reload table finally.

Let’s run it and see everything is working fine. Yes all good till now.

Let’s refactor code of updation.


In ViewController search for

method. We will copy this method as it is and paste it in CoreDataManager class.

Now open ViewController file and change implementation of

method to as per below implementation:

Look at the code man! We shredded a lot of weight from this method. Cheers 🙂

Build it, insert some data and update it, it should work.

Now lets change delete implementation and make delete available in CoreDataManager class. Copy complete delete(person:) function with it’s implementation from ViewController and paste in CoreDataManager class.

Explanation pretty simple. Get managed object context. Call delete method and pass person object as parameter. Finally call do-try-catch to save uncommitted changes of managedContext.

Now change

implementation as below:

Are you looking at this code  😎 . So light weight. Let’s again build, run and test insert, update and delete code, everything should work fine.

Finally lets quickly refactor code of fetchAllPersons() and then func delete(ssn: String).

Open CoreDataManager class and paste below code:

Make minor changes in above code:

Now we will refactor code for delete function, which uses predicate.

Paste below method in CoreDataManager class.

change implementation of

in ViewController class as below:

Explanation – We are using swift high order function filter, to remove objects of arrRemovedObjects from people array.


You can also create your own logic using for loop  😉 .

Let’s run our code and test all operations. Every thing is working perfect.

😀  😎  😉 .

As promised Sourcecode is here.

Please support us by comment, like and share our facebook page.