Database Reference
In-Depth Information
Therefore, understanding how contexts work is very important! Here are some
things you may have already picked up from the topic so far:
A context is an in-memory scratchpad for working with your managed objects.
You do all of the work with your Core Data objects within a managed object
context.
Any changes you make won't affect the underlying data on disk until you call
save() on the context.
Now here are five things about contexts that weren't mentioned before. A few of
them are very important for later chapters, so pay close attention:
1. The context manages the lifecycle of the objects that it creates or fetches. This
lifecycle management includes powerful features such as faulting, inverse
relationship handling and validation.
2. A managed object cannot exist without an associated context. In fact, a
managed object and its context are so tightly coupled that every managed object
keeps a reference to its context, which can be accessed like so:
let employeeContext = employee. managedObjectContext
3. Contexts are very territorial; once a managed object has associated with a
particular context, it will remain associated with the same context for the duration
of its lifecycle.
4. An application can use more than one context—most non-trivial Core Data
applications fall into this category. Since a context is an in-memory scratch pad
for what's on disk, you can actually load the same Core Data object onto two
different contexts simultaneously.
5. A context is not thread safe. The same goes for a managed object—you can only
interact with contexts and managed objects on the same thread in which they
were created. Apple has provided many ways to work with contexts in
multithreaded applications. You'll read all about different concurrency models in
Chapter 10, “Multiple Managed Object Contexts.”
Creating your stack object
Now that you know what each component does, it's time to return to Dog Walk and
implement your own Core Data stack.
As you know from previous chapters, Xcode creates its Core Data stack in the app
delegate. You're going to do it differently. Instead of mixing app delegate code with
Core Data code, you'll create a separate class to encapsulate the stack.
Go to File\New\File… , select the iOS\Source\Swift File template and click
Next . Name the file CoreDataStack and click Create to save the file.
 
Search WWH ::




Custom Search