Sort NSArray with custom objects

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 a subclass of UITableViewController, there is an NSArray containing many unsorted LDLocations. Now I want to sort NSArray objects in ascending order, depending on the city of LDAddress properties.

How can I sort an array using NSSortDescriptor? I tried the following, but it is reset when the application loads.

 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Address.city" ascending:YES]; [_locations sortedArrayUsingDescriptors:@[sortDescriptor]]; 
+8
sorting ios objective-c nssortdescriptor
source share
4 answers

Try making the first key lowercase.

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

You can also sort an array with blocks:

  NSArray *sortedLocations = [_locations sortedArrayUsingComparator: ^(LDAddress *a1, LDAddress *a2) { return [a1.city compare:a2.city]; }]; 
+14
source share

This will allow you to sort several types. Like we need to sort the movie by time, and if the time is equal, then we need to sort by name.

 NSArray *sortedArray = [childrenArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { NSNumber *first = [NSNumber numberWithLong:[(Movie*)a timeInMillis]]; NSNumber *second = [NSNumber numberWithLong:[(Movie*)b timeInMillis]]; NSComparisonResult result = [first compare:second]; if(result == NSOrderedSame){ result = [((NSString*)[(Movie*)a name] ) compare:((NSString*)[(Movie*)b name])]; } return result; }]; 
+3
source share
 -(NSArray*)sortedWidgetList:(NSArray*)widgetList { NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"itemNum" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil]; NSArray *sortedArray = [widgetList sortedArrayUsingDescriptors:sortDescriptors]; return sortedArray; } 
+1
source share

All Articles