8

在我的 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 对象。现在,我想根据LDAddress的属性城市对 NSArray 的对象进行升序排序。

如何使用 NSSortDescriptor 对数组进行排序?我尝试了以下操作,但是在对数组进行排序时应用程序会转储。

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

4 回答 4

14

尝试将第一个键设为小写。

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address.city" ascending:YES];
于 2012-06-01T15:47:02.470 回答
14

您还可以使用块对数组进行排序:

    NSArray *sortedLocations = [_locations sortedArrayUsingComparator: ^(LDAddress *a1, LDAddress *a2) {
        return [a1.city compare:a2.city];
    }];
于 2012-06-01T15:49:26.243 回答
3

这将允许使用多种类型进行排序。就像我们需要根据时间对电影进行排序,如果时间相等,则需要按名称排序。

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;
    }];
于 2014-08-01T10:28:01.977 回答
1
-(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;
}
于 2015-05-18T06:54:54.177 回答