亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我現在的做法是遍歷數組然后排序的辦法,感覺這樣好麻煩,還有其他方式嗎?

我現在的做法是遍歷數組然后排序的辦法,感覺這樣好麻煩,還有其他方式嗎?

iOS
九州編程 2023-04-14 22:18:41
我有這樣一個數組:NSArray *arr = @[@{@"index" : @"3", @"key" : @"value"},                  @{@"index" : @"4", @"key" : @"value"},                  @{@"index" : @"1", @"key" : @"value"},                  @{@"index" : @"2", @"key" : @"value"}];要重新按照字典里的index值排序變成這樣:NSArray *arr = @[@{@"index" : @"1", @"key" : @"value"},                  @{@"index" : @"2", @"key" : @"value"},                  @{@"index" : @"3", @"key" : @"value"},                  @{@"index" : @"4", @"key" : @"value"}];
查看完整描述

2 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

NSArray *array = [NSArray array];
    [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSNumber index1 = [obj1 valueForKey:@"index"];
        NSNumber index2 = [obj2 valueForKey:@"index"];        return [index1 compare:index2];
    }];

就是這樣了。


查看完整回答
反對 回復 2023-04-17
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];}
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)
or usually even better: (The default sorting selector of NSSortDescriptor is compare:)

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

Blocks (shiny!)

There's also the possibility of sorting with a block since 10.6:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];    return [first compare:second];
}];


查看完整回答
反對 回復 2023-04-17
  • 2 回答
  • 0 關注
  • 154 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號