【问题标题】:sort NSMutablearray having range objects对具有范围对象的 NSMutablearray 进行排序
【发布时间】:2012-08-13 13:56:52
【问题描述】:

我已将范围对象添加到 NSMutable 数组,即 [{5, 12} {0, 4} {18, 10}]。现在我想按升序对这个 NSMutable 数组进行排序。我正在使用以下代码按递增顺序获取 NSMutable 数组对象。

        NSArray *stringIndexes = [StringIndexes copy];
        stringIndexes = [stringIndexes sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"stringIndexes..:%@",stringIndexes);

但它没有提供所需的输出。如果有人知道如何对具有范围对象的 NSMutable 数组进行排序。请帮帮我。

谢谢大家。

【问题讨论】:

  • 如何将NSRange 添加到可变数组中? NSRange 不是一个对象,它是一个结构体。
  • 我已将 NSRange 添加到 nsmutable 数组中。
  • NSRange 不是 Objective-C 对象...如果您尝试添加 NSRange,则显示错误““NSRange”类型的集合元素(又名 _NSRange)不是 Objective-C 对象。
  • '我已将 NSRange 添加到 nsmutable 数组' - 如何?为您的问题添加一些代码!
  • 您可能应该将问题标题更改为“如何对 NSStrings 数组进行排序”

标签: iphone objective-c ios


【解决方案1】:

如果要向数组添加范围,请使用

NSValue *value = [NSValue valueWithRange:(NSRange)range];

当你想对数组进行排序时:

[myArray sortUsingComparator:^NSComparisonResult(NSValue *val1, NSValue *val2, BOOL *stop) {
  NSRange range1 = [val1 rangeValue];
  NSRange range2 = [val2 rangeValue];
  // you need to fine tune the test below - not sure what you want
  if(range1.location == range2.location) return NSOrderedSame;
  if(range1.location < range2.location) return NSOrderedAscending;
  if(range1.location > range2.location) return NSOrderedDescending;
  assert(!"Impossible");
  } ];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多