我有這樣一個(gè)數(shù)組: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秒到達(dá)戰(zhàn)場
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
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]; }];
就是這樣了。

慕尼黑5688855
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
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]; }];
- 2 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)
0/150
提交
取消