2011-09-27 71 views
0

我有一个NSArray。可以说我内部有3个物体。例如array position objective-c

test (
     { 
     Code = A; 
     Comment = "None "; 
     Core = Core; 
},{ 
     Code = B; 
     Comment = "None "; 
     Core = Core; 
},{ 
     Code = C; 
     Comment = "None "; 
     Core = Core; 
}) 

我想搜索'代码'并返回数组索引。我怎样才能做到这一点?例如找到代码'b',我会返回'​​1'(因为它是数组中的第二个位置)。

回答

2

关闭我的头顶,所以可能会有一些错别字。我假设你的数组中的对象是字典:

for (NSDictionary dict in testArray) 
{ 
    if ([[dict objectForKey:"Code"] isEqualToString:@"B"] 
    { 
     NSLog (@"Index of object is %@", [testArray indexOfObject:dict]); 
    } 
} 

您也可以使用(可能更有效)

- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate 

传球@"Code == 'B'"谓词的块。该方法将特别返回通过测试的对象的索引。

0

如果面向iOS 4.0或更高版本,有NSArray方法允许您使用块进行此操作。

– indexOfObjectPassingTest:
– indexesOfObjectsPassingTest:
等。

NSArray *test = [NSArray arrayWithObjects: 
       [NSDictionary dictionaryWithObjectsAndKeys:@"A", @"Code", @"None", @"Comment", @"Core", @"Core", nil], 
       [NSDictionary dictionaryWithObjectsAndKeys:@"B", @"Code", @"None", @"Comment", @"Core", @"Core", nil], 
       [NSDictionary dictionaryWithObjectsAndKeys:@"C", @"Code", @"None", @"Comment", @"Core", @"Core", nil], 
       nil]; 
NSIndexSet *indexes =[test indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { 
    return [[obj valueForKey:@"Code"] isEqualToString:@"B"]; 
}]; 

NSLog(@"Indexes with Code B: %@", indexes); 
0

最简单的形式,我会用以下内容:

- (NSInteger)indexForText:(NSString*)text inArray:(NSArray*)array 
{ 
    NSInteger index; 
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    YourObject* o = (YourObject*)obj; 
    if ([[o property] isEqualToString:text]) { 
     index = idx; 
     *stop = YES; 
    } 
    }]; 
    return index; 
}