简体   繁体   中英

sort NSMutablearray having range objects

I have add the range objects to NSMutable array ie [{5, 12} {0, 4} {18, 10}]. Now I want to sort this NSMutable array in increasing order. I am using the following code to get the NSMutable array objects in increasing order.

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

But it is not giving the required output. If anyone know that how to sort the NSMutable array having range objects. Please help me out.

Thanks to all.

If you want to add ranges to an array, use

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

When you want to sort the array:

[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");
  } ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM