0

I am trying to search for a string within an array, but I only want to search the last five objects in the array for the string.

I have been fiddling with every parameter I can find on NSRange to no avail.

I would post some example code, but I can't even get out the line I need, whether its through introspection, enumeration, or just some NSRange call that I missed.

jakenberg
  • 2,125
  • 20
  • 38

3 Answers3

2

If your array elements are strings that you searched for, you can directly check the array as follows:

if ([yourArray containsObject:yourString])
{
     int index = [yourArray indexOfObject:yourString];

     if (index>= yourArray.count-5)
     {
          // Your string matched
     }
}
Anusha Kottiyal
  • 3,855
  • 3
  • 28
  • 45
1

I like indexesOfObjectsWithOptions:passingTest: for this. Example:

    NSArray *array = @[@24, @32, @126, @1, @98, @16, @67, @42, @44];
    // run test block on each element of the array, starting at the end of the array
    NSIndexSet *hits = [array indexesOfObjectsWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        // if we're past the elements we're interested in
        // we can set the `stop` pointer to YES to break out of
        // the enumeration
        if (idx < [array count] - 5) {
            *stop = YES;
            return NO;
        }
        // do our test -- if the element matches, return YES
        if (40 > [obj intValue]) {
            return YES;
        }
        return NO;
    }];
    // indexes of matching elements are in `hits`
    NSLog(@"%@", hits);
Art Gillespie
  • 8,747
  • 1
  • 37
  • 34
0

Try this :-

//Take only last 5 objects
NSRange range = NSMakeRange([mutableArray1 count] - 5, 5);
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithArray:
                                  [mutableArray1 subarrayWithRange:range]];
//Now apply search logic on your mutableArray2
for (int i=0;i<[mutableArray2 count];i++)
    {
        if ([[mutableArray2 objectAtIndex:i] isEqualToString:matchString])
        {
            //String matched
        }
    }

Hope this helps you!

P.J
  • 6,547
  • 9
  • 44
  • 74