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 のサブクラスには、LDLocations のソートされていないオブジェクトを多数含む NSArray があります。ここで、LDAddressのプロパティcityに基づいて昇順で 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

これにより、複数のタイプでソートできます。時間に基づいて Movie を並べ替える必要があるように、時間が等しい場合は名前で並べ替える必要があります。

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 に答える