0
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Ok, I think I've found an answer that I can appreciate. From Marcus Zarra's blog:

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.

source: http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/

Look's like I'll go back to passing the managed object context via Segue.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.