0

As an example if I have this array:

_mode = [NSArray arrayWithObjects:
                      [NSArray arrayWithObjects:@"1", @"One", nil],
                      [NSArray arrayWithObjects:@"2", @"Two", nil],
                      [NSArray arrayWithObjects:@"3", @"Three", nil],
                      [NSArray arrayWithObjects:@"4", @"Four", nil],
                      [NSArray arrayWithObjects:@"5", @"Five", nil],
                      nil];

and I need to find which object of array _mode contains @"3" how would I do that? I have tried selectedIndex = [_mode indexOfObject:@"3"]; and selectedIndex = [[_mode objectAtIndex:0] indexOfObject:@"sta"]; but neither work.

4 Answers 4

9
[_mode indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    return [[obj objectAtIndex:0] isEqualToString:@"3"];
}];
Sign up to request clarification or add additional context in comments.

6 Comments

Unless you know the object you are looking for is always at index 0 this approach will need an extra for loop inside the block
Nice solution. But be informed: Available in iOS 4.0, Mac OS X v10.6 and later.
@nacho4d, if the target is not necessarily at index 0, just use [obj containsObject:@"3"].
Sure it does a loop. You have to examine the elements somehow. The point is to not write that loop yourself if you can avoid it. The code will be more readable, more compact, and less prone to error.
The object is always at index 0 of the subarray. This works perfect. Thanks.
|
3

This is basically the same as Jonas Schnelli answer :)

for (NSArray *subarray in _mode){
    NSInteger index = [subarray indexOfObject:@"3"];
    if (index != NSNotFound) return subarray;
}

Comments

2

like this?

for(NSArray *subarray in _mode) {
  for(NSString *str in subarray) {
   if([str isEqualToString:@"3"]) {
     return subarray; // returns the array within _mode that contains "3"
   }
  }
}

if you need the index:

for(NSArray *subarray in _mode) {
  for(NSString *str in subarray) {
   if([str isEqualToString:@"3"]) {
     return [mode indexOfObject:subarray];
   }
  }
}

Comments

2

This gives a index of a dictionary which is in array.

for (NSDictionary *dict in self.yourArray ) {
    if ([anotherArray containsObject:[dict valueForKey:@"Key"]]) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.yourArray indexOfObject:dict] inSection:section];
        NSLog(@"IndexPath is %@",indexPath);
    }    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.