Ben Packard
Ben Packard

Reputation: 26476

Passing around an NSManagedObjectContext

My Core Data stack is set up in the AppDelegate as usual. I am a good OO citizen and recognize that accessing it directly via [[UIApplication sharedApplication] delegate] managedObjectContext] (or moving it to some singleton) is global state/code smell/naughty.

But the controller that needs to access the data is about five layers deep. There are container controllers and modals and bears in between. Am I supposed to pass the context down through each layer simply so that the last screen can spit out a list of entities? Seems like this restricts reusability, increases complexity, and decreases understandability.

Upvotes: 0

Views: 233

Answers (2)

Ricardo Sanchez-Saez
Ricardo Sanchez-Saez

Reputation: 9566

Look at Magical Record, it provides lots of convenience methods for all kinds of Core Data typical usage cases.

With it, you don't need to manually keep track of your context, the convenience methods automatically access it (them) in a thread safe way.

It also suports background model saving and less boilerplatery fetching.

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 6352

Yes you are supposed to pass it around as per Apples recommendations. However I have been lazy in some circumstances and just grabbed it off the App delegate because I'm not doing anything multi-threaded computing. I try most of the time to stick to Apples guideliness and make sure I pass the context around by default so If I ever need it lower I have it.

"A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid."

Check out the iOS info that apple recommends https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html

Upvotes: 1

Related Questions