4 ms·
I'd suggest using multiple contexts more, not less, in applications. I'll generally use a shared "Library" instance to mediate access to data in a shoebox-styl
by eschaton 13y ago
I'd suggest using multiple contexts more, not less, in applications.
I'll generally use a shared "Library" instance to mediate access to data in a shoebox-style (as opposed to document-style) app. The Library has a root context with private queue concurrency, and has methods used by other parts of the app to obtain new child contexts: One to create a new main-queue child context, and one to create a new background (private-queue) context. The root context is never directly vended, and neither are objects from it; it's primarily used to save changes propagated from the child contexts, and the Library accomplishes this by observing the did-save notifications for child contexts it creates. When it saves, it also posts its own notification (wrapping the root context's did-save notification) so any longer-lived contexts can merge changes upwards from the root.
So in some piece of UI, such as a window controller on OS X or a view controller on either OS X or iOS, I'll ask the Library for a new main-queue context and use that to present that UI—and only that UI. If I need to perform some calculations or a background update (say from a web service), I'll ask the Library for a new background context and use it for just that operation. Any save in either case triggers a subsequent save by the Library's root context, and a notification of that which can be used to update other child contexts.
And any time I'm passing objects around, I use managed object IDs rather than the objects themselves, so there's no concern about mixing objects from different contexts.
With the above in mind, it winds up being pretty straightforward to build nicely-performing apps that use Core Data to persist their object graphs.
- tomwilson 13y agoI've been taking this approach in a new app I've been working on and it certainly seems like the way to go.