Database Reference
In-Depth Information
var
sd =
NSSortDescriptor
(key:
"priceInfo.priceCategory"
,
ascending:
true
)
return
sd
}()
The way to add sorts is very similar to the way you added filters. Each sort maps to
one of these three lazy
NSSortDescriptor
properties.
To initialize an instance of
NSSortDescriptor
you need three things: a key path to
specify the attribute by which you want to sort, a specification of whether the sort
is ascending or descending and an optional selector.
Note:
If you've worked with
NSSortDescriptor
before, then you probably know
there's a block-based API that takes a comparator instead of a selector.
Unfortunately, Core Data doesn't support this way of defining a sort
descriptor.
The same thing goes for the block-based way of defining an
NSPredicate
. Core
Data doesn't support this either. The reason is related to the fact that
filtering/sorting happens in the SQLite database, so the predicate/sort
descriptor has to match nicely to something that can be written as an SQLite
statement.
The three sort descriptors are going to sort by name, distance and price category,
respectively, and they are all ascending. Before moving on, take a closer look at the
first sort descriptor,
nameSortDescriptor
. The initializer takes in an optional selector
called
localizedStandardCompare
. What is that?
Any time you're sorting user-facing strings, Apple recommends that you pass in
localizedStandardCompare
to sort according to the language rules of the current
locale. That means the sort will “just work” and do the right thing for languages
with accented characters, for example. It's the little things that matter. :]
Next, go down to
didSelectRowAtIndexPath
and add the following cases to the end
of the
switch
statement:
//Sort By section
case
nameAZSortCell
:
selectedSortDescriptor
=
nameSortDescriptor
case
nameZASortCell
:
selectedSortDescriptor
=
nameSortDescriptor
.
reversedSortDescriptor
as
?
NSSortDescriptor
case
distanceSortCell
:
selectedSortDescriptor
=
distanceSortDescriptor
case
priceSortCell
: