简体   繁体   中英

Finding the location (index) of a NSRange in NSArray using ObjectAtIndex

I'm trying to find this NSRange location (index) in a NSArray:

NSValue *findRangeValue = [NSValue valueWithRange:NSMakeRange(146, 143)];

I'm able to find the location using the method indexOfObject:

NSUInteger integer = [mutArray indexOfObject:findRangeValue];
//This returns (5) which is correct!

But how can I find the NSRange's location (index) in my NSArray by only having the NSRange's length (143), and achieve the same result as above?

  • Thanks in advance, Dan

You can use the indexOfObjectPassingTest: method on your array.

 int desiredRange = 152;
 NSUInteger integer = [objects indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
      NSValue *range = (NSValue*)obj;
      if([range rangeValue].length == desiredRange)
      {
          *stop = true;
          return YES;
      }
      return NO;
  }];

Since you are only checking a part of the object there may be multiple objects that match your search. If you need an array of these things you can either do a custom search through the array or you can create an array based on your search results (just never return that you found the correct result and it will continue the search as you fill your answers array).

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