Refactoring the persistence code

Many iOS developers dislike the amount of boilerplate code that is involved with using Core Data. Simply persisting an object requires you to repeat several lines of code, which can become quite a pain to write and maintain over time. The approach to refactoring the persistence code presented in the following examples is heavily inspired by the approach taken in the Core Data book written by Florian Kugler and Daniel Eggert.

If you're interested in learning more about Core Data outside of what this book covers, and if you'd like to see more clever ways to reduce the amount of boilerplate code, you should pick up this book.

One pattern you can find in both save methods is the following:

moc.perform {   
  // create managed object   

  do {   
    try moc.save()   
  } catch {   
    moc.rollback()   
  }   
}

It would be great if you could write the following code to persist data instead:

moc.persist {   
    // create managed object   
} 

This can be achieved by writing an extension for NSManagedObjectContext. Add a file called NSManagedObjectContext to the extensions folder, and add the following implementation:

import CoreData   

extension NSManagedObjectContext {   
  func persist(block: @escaping () -> Void) {
    perform {
      block()

      do {
        try self.save()
      } catch {
        self.rollback()
      }
    }
  }  
} 

The preceding code allows you to reduce the amount of boilerplate code, which is something that you should always try to achieve. Reducing boilerplate code greatly improves your code's readability and maintainability. Update both the family overview and the movie list view controllers to make use of this new persistence method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.48.62