Jason Brady Jason Brady - 6 months ago 11
iOS Question

Should I make a new managedObjectContext for each ViewController Swift

I was wondering what was the best practice for doing the

managedObjectContext
. When I first started learning swift / iOS / Xcode earlier this year I was putting this line in every class for the ViewControllers / TableViewControllers.

let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext


And everything was working correctly. But then I thought I read something at some point that said to use the same
managedObjectContext
for every ViewController / TableViewController. And I interpreted this to mean to send my original moc variable to each ViewController / TableViewController. To do this I started sending it in the 'prepareForSegue' function. So only the first view had the code above, and everything else just had
var moc: NSManagedObjectContext?
that would get set from the
prepareForSegue
Function.

But the more I learn, I'm starting to think that the AppDelegate is creating the actual
managedObjectContext
and the
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
line is just setting that
managedObjectContext
to the moc variable, and not actually making a new
managedObjectContext
.

So should I be continuing to use the
prepareForSegue
function to send my moc variable to all the linked ViewControllers / TableViewControllers, or should I not worry about it and be setting it using the code at the top?

Thank you.

Answer
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

this is perfectly fine as it does not create a new context, but just gives you a new reference to the same context. In fact it is in no way different from "sending original moc variable in the 'prepareForSegue' function". You're doing exactly the same thing in two different ways, that's it.

Read about value and reference types in Swift: Classes and structures