Sort NSArray with custom objects

PhilippS picture PhilippS · Jun 1, 2012 · Viewed 14.2k times · Source

In my Xcode project I have the following classes:

Address

@interface LDAddress : NSObject{
    NSString *street;
    NSString *zip;
    NSString *city;
    float latitude;
    float longitude;
}

@property (nonatomic, retain) NSString *street;
@property (nonatomic, retain) NSString *zip;
@property (nonatomic, retain) NSString *city;
@property (readwrite, assign, nonatomic) float latitude;
@property (readwrite, assign, nonatomic) float longitude;

@end

Location

@interface LDLocation : NSObject{
    int locationId;
    NSString *name;
    LDAddress *address;
}
@property (readwrite, assign, nonatomic) int locationId;
@property (nonatomic, retain) LDAddress *address;
@property (nonatomic, retain) NSString *name;

@end

In an subclass of UITableViewController, there is a NSArray containing a lot of unsorted objects of LDLocations. Now, I want to sort the NSArray's objects ascending based on the property city of a LDAddress.

How can I sort the array using NSSortDescriptor? I tried the following, but the app dumps when sorting the array.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Address.city" ascending:YES];
[_locations sortedArrayUsingDescriptors:@[sortDescriptor]];

Answer

kubi picture kubi · Jun 1, 2012

Try making the first key lowercase.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address.city" ascending:YES];