Database Reference
In-Depth Information
Once again, you execute the fetch request against
CoreDataStack
's
NSManagedObjectContext
property. Then you extract the integer from the resulting
NSNumber
and use it to populate
firstPriceCategoryLabel
.
Before you run the sample app, implement
viewDidLoad
to invoke the method you
just implemented:
override
func
viewDidLoad() {
super
.
viewDidLoad
()
populateCheapVenueCountLabel
()
}
Now build and run to test if these changes took effect. Tap
Filter
to bring up the
filter/sort menu:
The label under the first price filter now says “27 bubble tea places.” Hooray!
You've successfully used
NSFetchRequest
to calculate a count.
Note:
You may be thinking that you could have just as easily fetched the
actual
Venue
objects and gotten the count from the array's
count
property.
That's true. Fetching counts instead of objects is mainly a performance
optimization. For example, if you had census data for New York City and
wanted to know how many people lived in its metropolitan area, would you
prefer Core Data gave you the number 8,300,000 (an integer) or an array of
8,300,000 records? Obviously, getting the count directly is more memory-
efficient.
There's a whole chapter devoted to Core Data performance. If you want to
learn more about performance optimization in Core Data, check out Chapter 9,
“Measuring and Boosting Performance.”