Sorting array of custom objects based on nested object

Sorting an array of custom objects is not a big deal. NSSortDescriptor works awesome for this. Lets take an example

#import <Foundation/Foundation.h>
@interface Parent : NSObject
@property(strong, nonatomic) NSString *name;
@end
@interface Child : NSObject
@property(strong, nonatomic) NSString *name;
@property(strong, nonatomic) Parent *parent;
@end
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *sortedArray = [childrenArray sortedArrayUsingDescriptors:sortDescriptors];

Now what if I want to sort the children array based on name of parent. Parent is a composed within Child. We can use NSComparisonResult. Lets modify the Child.m

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

Our sorting will be:

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

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>