I've been experimenting with how to pass my managed object context throughout my application in Core Data and I came across an approach that I'd like reviewed.
I've been creating a protocol for all of my View Controllers that need a managed object context to implement:
protocol ManagedObjectContextProperty {
var managedObjectContext: NSManagedObjectContext! { get set }
}
Then I create an extension to that protocol to assert that the context does indeed exist:
extension ManagedObjectContextProperty {
func checkManagedObjectContext(name: String) {
if managedObjectContext == nil {
assertionFailure("\(name) is missing the managed object context.")
}
}
}
Finally, I create an extension that fetches my context from the app delegate and add's it to my managedObjectContext
variable:
extension UIViewController {
func getManagedObjectContext<T : UIViewController where T : ManagedObjectContextProperty>(controller: T) {
var controller = controller
let appDelegate = UIApplication.shared().delegate as! AppDelegate
controller.managedObjectContext = appDelegate.managedObjectContext
}
}
Then in my View Controller I simply do this:
class ViewController: UIViewController, ManagedObjectContextProperty {
var managedObjectContext: NSManagedObjectContext!
override func viewDidLoad() {
getManagedObjectContext(controller: self)
checkManagedObjectContext(name: "ViewController")
}
}
Is this approach is against the general convention? If so, why?