Sort NSArray of custom objects with more nesting

by

Sorting an array of custom objects is fair simple. NSSortDescriptor works awesome for this. Lets see an example:


@interface Parent : NSObject
@property(strong, nonatomic) NSString *name;
@end
NSArray *arrayOfParents = @[parent1, parent2];

If I want to sort array of parents by their name then I would use something like:


 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey : @"name" ascending : YES];

Let’s get more nesting by introducing another custom type inside class by composition. I create new class Child with our earlier declared Parent class inside it via composition.


@interface Child : NSObject
@property(strong, nonatomic) NSString *name;
@property(strong, nonatomic) Parent *parent;
@end
NSArray *arrayOfChildren = @[child1, child2];
I want to sort children by the name of their parents. Earlier I sorted by object’s property but now I want to sort bt property of nested object.

For this purpose I use flexible NSComparisonResult by implementing compare: that returns the result inside the class:


#import “Child.h”
@implementation Child
- (NSComparisonResult)compare:(Child *)otherObject {
    return [self.parent.name compare:otherObject.parent.name];
}
@end

Sorting becomes:


NSArray *sortedArray = [arrayOfChildren sortedArrayUsingSelector:@selector(compare:)];

More Articles

Recommended posts