简体   繁体   English

使用ObjectAtIndex在NSArray中查找NSRange的位置(索引)

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

I'm trying to find this NSRange location (index) in a NSArray: 我正在尝试在NSArray中找到此NSRange位置(索引):

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

I'm able to find the location using the method indexOfObject: 我可以使用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? 但是,如何仅具有NSRange的长度(143)来在NSArray中找到NSRange的位置(索引),并获得与上述相同的结果?

  • Thanks in advance, Dan 预先感谢,丹

You can use the indexOfObjectPassingTest: method on your array. 您可以在数组上使用indexOfObjectPassingTest:方法。

 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). 如果您需要这些东西的数组,则可以通过该数组进行自定义搜索,也可以根据搜索结果创建一个数组(只是永远不要返回找到正确结果的数组,当您填写答案时它将继续搜索数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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