Database Reference
In-Depth Information
For instance, whenever you make a change to a GUI widget, it is recommended
you be on the main thread, because the UI is not thread-safe.
Prior to iOS 6.0 and OS X 10.8 Mountain Lion, you could get away with using
Core Data incorrectly in a multithreaded environment. If you read from
NSManagedObject instances only on threads other than the one that created the
instance and didn't write to them, then things would work—usually. However,
as of iOS 6.0 and OS X 10.8 Mountain Lion, that has changed. Core Data
now monitors what thread the objects are being accessed from and will throw
an exception if an improper access is detected. While this change can catch
developers off-guard, it is a net win. We now have well-defined boundaries
for what is correct and what is not.
Whether we are developing for the latest release of iOS or OS X or targeting
an older platform, we must now follow a strict rule for thread safety with Core
Data: contexts and their resulting objects must be accessed only on the thread
that created them.
NSOperation and NSOperationQueue
Throughout this chapter we will be using NSOperation and NSOperationQueue quite heavily.
These are classes that were added to Cocoa as part of Mac OS X 10.5 Leopard
specifically to make threading easier. Although we will not be going into detail on
how to use these classes, it is of extreme value to fully learn these classes so that
you can use them properly in your own projects.
There's a naming issue that often causes confusion while using NSOperation . The
NSOperation uses a method named -main as the entry point for the work that the NSOper-
ation is to complete while running on a background thread. The NSOperationQueue calls
this method directly. However, if the NSOperation is flagged as being concurrent, then
the NSOperationQueue will call -start instead. In all of the examples presented in this topic,
we will be using the “ nonconcurrent” (which translates into “ threaded” ) implementation
of NSOperation and therefore using the -main entry point.
5.2
Creating Multiple Contexts
As of iOS 6.0 and Mac OS X Lion, there are two recommended methods for
using Core Data across multiple threads. The first method, which is valid on
all versions of iOS and Mac OS X that can use Core Data, involves creating
a separate NSManagedObjectContext for each thread that will be interacting with
Core Data. 1 The creation of the separate context on a background thread is
1.
We will be exploring the second, updated method in Section 5.5, Parent-Child NSMan-
agedObjectContext Instances , on page 92 .
 
 
 
Search WWH ::




Custom Search