Lynn Gobin
Lynn Gobin

Reputation: 21

Sort NSArray containing multiple object classes

I am working with two types of entities: Person objects and a Department objects. The Person object has the properties last name, first name, department name and phone number. The Department object has the properties department name and phone number.

I am able to use NSFetchedResultsControllers to retrieve and sort the the Person and Department objects. How can I combine these results into a single array keyed on the last and first names for the Person objects and on the department name for the Department objects, like this:

    Accounting                                    5-5544
    Almond, Betty         Accounting              5-5544
    Almond, Robert        Shipping                5-4345
    Brown, John           Building Maintenance    5-5566
    Building Maintenance                          5-5566 ...

Upvotes: 2

Views: 385

Answers (2)

falcon143
falcon143

Reputation: 708

Example for first name and last name using sorting

Smith John Andersen Jane Clark Anne Smith David Johnson Rose

Sort using NSDescriptor

Sort descriptors can be used not just for sorting arrays but also to specify how the elements in a table view should be arranged and also with Core Data to specify the ordering of objects returned from a fetch request. With sort descriptors you can easily sort the array by multiple keys. We’ll sort our array by surname and then by name.

NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"surname" ascending:YES];
NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, secondDescriptor, nil];

NSArray *sortedArray = [self.persons sortedArrayUsingDescriptors:sortDescriptors];

The resulting array will look like this:

Andersen Jane Clark Anne Johnson Rose Smith David Smith John

Upvotes: 1

dalton_c
dalton_c

Reputation: 7171

One example:

NSArray *combinedArray = [self.persons arrayByAddingObjectsFromArray:self.departments];
NSArray *sortedArray = [combinedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *name1 = ([obj1 isKindOfClass:[Person class]]) ? [[(Person *)obj1 lastName] stringByAppendingString:[(Person *)obj1 firstName]] : [(Department *)obj1 name];
    NSString *name2 = ([obj2 isKindOfClass:[Person class]]) ? [[(Person *)obj2 lastName] stringByAppendingString:[(Person *)obj2 firstName]] : [(Department *)obj2 name];

    return [name1 caseInsensitiveCompare:name2];
}];

Upvotes: 0

Related Questions