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]];
The in-built sort () method can sort an array of objects. The sort method takes an array of elements and returns the sorted array. It accepts an optional function that can be used to specify the sort order of the returned array. //1.
In the main () method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use list 's sort () method. The sort () method takes the list to be sorted (final sorted list is also the same) and a comparator.
The sort () method takes the list to be sorted (final sorted list is also the same) and a comparator. and finally returns positive number if o1's property is greater than o2's, negative if o1's property is lesser than o2's, and zero if they are equal.
For sorting the list with the given property, we use list 's sort () method. The sort () method takes the list to be sorted (final sorted list is also the same) and a comparator. and finally returns positive number if o1's property is greater than o2's, negative if o1's property is lesser than o2's, and zero if they are equal.
Try making the first key lowercase.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address.city" ascending:YES];
You can also sort an array with blocks:
NSArray *sortedLocations = [_locations sortedArrayUsingComparator: ^(LDAddress *a1, LDAddress *a2) {
return [a1.city compare:a2.city];
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With