用自定义对象sortingNSArray
在我的Xcode项目中,我有以下类:
地址
@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
位置
@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
在UITableViewController的子类中,有一个NSArray包含许多LDLocations未sorting的对象。 现在,我想根据LDAddress属性城市对NSArray的对象进行升序sorting。
我怎样才能使用NSSortDescriptorsorting数组? 我尝试了以下,但sorting数组时,应用程序转储。
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Address.city" ascending:YES]; [_locations sortedArrayUsingDescriptors:@[sortDescriptor]];
尝试使第一个关键小写。
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address.city" ascending:YES];
您也可以用块对数组sorting:
NSArray *sortedLocations = [_locations sortedArrayUsingComparator: ^(LDAddress *a1, LDAddress *a2) { return [a1.city compare:a2.city]; }];
这将允许sorting多种types。 就像我们需要根据时间对电影进行sorting,如果时间相等,则需要按名称sorting。
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; }];
-(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; }