【问题标题】:Sorted NSIndexSet of sub array of NSArrayNSArray 的子数组排序后的 NSIndexSet
【发布时间】:2016-01-24 20:39:13
【问题描述】:

假设我有NSIndexSet 的数组索引。 我想对这个NSIndexSet 进行排序取决于NSArray

所以,假设我们有数组:

array = @[1,4,3,8,6,2,9];

和索引集

indexSet :  (2,4,5,6)

所以这个索引的“子数组”将是

subArray = @[3,6,2,9]

所以我想要的是:

I have :
indexSet : (2,4,5,6)
array = @[1,4,3,8,6,2,9];
return indexSet : (5,2,4,6) --> this are sorted indexes of "sub array".

如何做到这一点?

【问题讨论】:

  • 这只会创建“子”数组,不会返回排序索引的 NSIndexSet...
  • 抱歉,误读了。忘记了你问题的最后一部分。

标签: ios sorting nsarray nsindexset


【解决方案1】:

你无法实现你想要的。 NSIndexSet 不维护与索引本身的顺序分开的顺序。它始终按索引顺序排列。

您可以构建一个数字对象数组,将其视为索引。

NSArray* array = /* ... */;
NSMutableArray* indexes = [[NSMutableArray alloc] init];
[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){
    [indexes addObject:@(idx)];
}];
[indexes sortUsingComparator:^NSComparisonResult(NSNumber* obj1, NSNumber* obj2){
    NSUInteger index1 = obj1.unsignedIntegerValue;
    NSUInteger index2 = obj2.unsignedIntegerValue;
    id element1 = array[index1];
    id element2 = array[index2];
    return [element1 compare:element2];
}];

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多