The first thing you see when you create new Project with CoreData template is ugly generated boilerplate code with that issues

  • Breaks Single Responsibility principle
  • The architecture doesn't scale well for bigger project,
  • It's a mess.
 // MARK: - Core Data stack

  lazy var managedObjectContext: NSManagedObjectContext? = {
      let coordinator = self.persistentStoreCoordinator
      if coordinator == nil {
          return nil
      }
      var managedObjectContext = NSManagedObjectContext()
      managedObjectContext.persistentStoreCoordinator = coordinator
      return managedObjectContext
  }()

  // MARK: - Core Data Saving support

  func saveContext () {
      if let moc = self.managedObjectContext {
          var error: NSError? = nil
          if moc.hasChanges && !moc.save(&error) {
            // Replace this implementation with code to handle the error appropriately.

            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
          }
      }
  }
 ....

There should be a better way to do this. And there is. -

Seru

Seru is light CoreData stack wrapper. It helps to setup and manage CoreData stack (Model, PersistenceCoordinator and Contexts).

Here is how CoreData setup looks in Seru.

class AppDelegate: UIResponder, UIApplicationDelegate {            
  lazy var persistence = PersistenceLayer()
  ...

Just one line of code. You can replace all the boilerplate code generated by apple with just one line. Isn't it amazing?

Seru provides way to handle all the CoreData issues in one place. By default Seru provide default error handler that will log error and generate crash log.

var handler = ErrorHandler(errorHandler: { error in
  // custom error handling for all issue related with CoreData
})
PersistenceLayer(name: "Example", errorHandler: handler)

Saving data is very easy as well. persist() method will save data to the disk

persistenceController.persist()

There are many more interesting thing that Seru does.
To see more details and Example project checkout code here
https://github.com/kostiakoval/Seru