15.6. Sorting Data in Core Data
Problem
You want to sort the managed objects (records) that you fetch from a managed object context (database).
Solution
Create instances of NSSortDescriptor
for each attribute (column,
in the database world) of an entity that has to be sorted. Add the sort
descriptors to an array and assign the array to an instance of NSFetchRequest
using the setSortDescriptors:
instance method. In this
example code, Sorting_Data_in_Core_DataAppDelegate
is the
class that represents the app delegate in a universal app. To understand
how the Person
entity is created,
please refer to Recipes 15.1 and 15.2:
-
(
BOOL
)
application:
(
UIApplication
*
)
application
didFinishLaunchingWithOptions:
(
NSDictionary
*
)
launchOptions
{
[
self
createNewPersonWithFirstName:
@"Richard"
lastName:
@"Branson"
age:
61
];
[
self
createNewPersonWithFirstName:
@"Anthony"
lastName:
@"Robbins"
age:
51
];
/* Create the fetch request first */
NSFetchRequest
*
fetchRequest
=
[[
NSFetchRequest
alloc
]
init
];
/* Here is the entity whose contents we want to read */
NSEntityDescription
*
entity
=
[
NSEntityDescription
entityForName:
@"Person"
inManagedObjectContext:
self
.
managedObjectContext
];
NSSortDescriptor
*
ageSort
=
[[
NSSortDescriptor
alloc
]
initWithKey:
@"age"
ascending:
YES
];
NSSortDescriptor
*
firstNameSort
=
[[
NSSortDescriptor
alloc
]
initWithKey:
@"firstName"
ascending:
YES
];
NSArray
*
sortDescriptors
=
[[
NSArray
alloc
]
initWithObjects:
ageSort
,
firstNameSort
,
nil
];
fetchRequest
.
sortDescriptors
=
sortDescriptors
;
/* Tell the ...
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.