A simple question about how the context is created and maintained in Chapter 3

Towards the end of Chapter 3, page 76-77, when ‘inserting the new walk into the Dog’s walks set’, you define the Walk entity and instantiate an object in context with the entity, and define the date value. Great! All understood.

BUT in the next section of code, you then use the currentDog property as if the context is definitely there. In viewDidLoad, the dog entity being defined and used in a fetch request, which if successful, transfers the results to currentDog; OR if not successful, the currentDog is given a context within the dog entity so that the dog’s name can be defined.

If the fetch is successful, does currentDog get its context when the request is assigned to currentDog?

That’s a great question! If I’m understanding you correctly, you want to know how currentDog gets its NSManagedObjectContext after you perform a fetch request and set a the result to it. Right?

When you perform a fetch request (managedContext.executeFetchRequest(fetchRequest)) all the objects you fetch get their context from the context you used to fetch them.

Things are even simpler for this sample app since there’s only one NSManagedObjectContext in the entire app that gets passed around. Hope that helps!

Thanks for the answer - that there’s one context that persists and is handed around the app. I guess, however, that in another app with more View Controllers, the context would be de-allocated when navigating to a new MVC unless it were specifically passed to the new View Controller.