Specifying Sorts Using NSSortDescriptor
Let’s assume, as an example, that we have an array (an instance of NSArray) containing instances of a custom class, Employee (that meets the requirements set out in “Requirements of Collection Objects”). The Employee class has attributes for an employee’s first and last name (instances of NSString), date of hire (an instance of NSDate), and age (an instance of NSNumber).
1:Sorting the array by the age key
ageDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES] autorelease]; sortDescriptors = [NSArray arrayWithObject:ageDescriptor]; sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
2:Sorting the array by the age and date of hire key
ageDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES] autorelease]; hireDateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"hireDate" ascending:YES] autorelease]; sortDescriptors = [NSArray arrayWithObjects:ageDescriptor, hireDateDescriptor, nil]; sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
Specifying Custom Comparisons
Sorting the array using a localized case insensitive comparison
lastNameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]; firstNameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]; sortDescriptors = [NSArray arrayWithObjects:lastNameDescriptor, firstNameDescriptor, nil]; sortedArray = [peopleArray sortedArrayUsingDescriptors:sortDescriptors];
The Foundation classes that have methods that can be used with sort descriptors are listed in Table 1.
Table 1 Common Foundation classes and comparison methods