Database Reference
In-Depth Information
memory is actually only on disk and has yet to be read into memory. Likewise,
objects that we think we are done with may actually still sit in a cache.
To demonstrate the differences in the ways that we can load data into memory
from our SQLite Store, I used an older Apple demonstration application from
a previous WWDC called GoFetch. (The source code for this application is
available as part of this topic's download.) The entire goal of this application
is to generate a large amount of random data and let us control how it is
fetched back into memory. Each fetch is then timed to demonstrate the speed
of various options. These tests were performed with 3,417 records in the
SQLite repository.
Loading NSManagedObjectID Objects Only
The smallest amount of data that we can retrieve as part of an
NSFetch-Request
is just the
NSManagedObjectID
. The
NSManagedObjectID
is the unique identifier for
the record and contains no content. In the test discussed earlier, it took the
test machine 0.004 seconds to retrieve 3,417 records from disk.
How to Retrieve NSManagedObjectID Objects
There is only one change required to retrieve just
NSManagedObjectID
objects
instead of full
NSManagedObject
objects.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@
"Person"
inManagedObjectContext:[self managedObjectContext]]];
[fetchRequest setResultType:NSManagedObjectIDResultType];
By changing the
-resultType
to
NSManagedObjectIDResultType
, our call to
-executeFetchRe-
quest:error:
returns
NSArray
of
NSManagedObjectID
objects instead of
NSManagedObject
objects.
Why would we want only the
NSManagedObjectID
objects? There are several uses
for this.
•
Inclusion comparison
: Since
NSManagedObjectID
objects guarantee uniqueness,
we can use them to determine whether an object is included in a set and
avoid having to retrieve the entire set for this comparison.
•
Prefetching
: Even though the properties for the associated objects are not
loaded into
NSManagedObject
objects for us to access, they are loaded into
a cache within Core Data. This means when we do access the associated
NSManagedObject
objects via a call to
objectWithID:
on
NSManagedObjectContext
, we
will get the results much faster than if we had to make a full round-trip
to the disk.