2011-09-27 2 views
0

NSArray가 있습니다. 내가 그 안에 3 개의 물건을 가지고 있다고하자. 예 :배열 위치 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]); 
    } 
} 

또한 블록에 @"Code == 'B'"의 술어를 통과

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

(아마도 더 효율적으로) 사용할 수 있습니다. 이 메서드는 테스트를 통과 한 객체의 인덱스를 반환합니다.

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; 
} 
관련 문제