作为一个例子,如果我有这个数组:
_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];
我需要找到数组_mode的哪个对象包含@"3"
我该怎么做?
我尝试了selectedIndex = [_mode indexOfObject:@"3"];
和selectedIndex = [[_mode objectAtIndex:0] indexOfObject:@"sta"];
,但都没有工作。
答案 0 :(得分:9)
[_mode indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
return [[obj objectAtIndex:0] isEqualToString:@"3"];
}];
答案 1 :(得分:3)
这与Jonas Schnelli的回答基本相同:)
for (NSArray *subarray in _mode){
NSInteger index = [subarray indexOfObject:@"3"];
if (index != NSNotFound) return subarray;
}
答案 2 :(得分:2)
for(NSArray *subarray in _mode) {
for(NSString *str in subarray) {
if([str isEqualToString:@"3"]) {
return subarray; // returns the array within _mode that contains "3"
}
}
}
如果您需要索引:
for(NSArray *subarray in _mode) {
for(NSString *str in subarray) {
if([str isEqualToString:@"3"]) {
return [mode indexOfObject:subarray];
}
}
}
答案 3 :(得分:2)
这给出了数组中字典的索引。
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);
}
}