2011-09-06 7 views

답변

23

. 당신이 당신의 배열 클래스의 이러한 종류의 개체를 여러 개있는 경우

// This will eventually contain the index of the object. 
// Initialize it to NSNotFound so you can check the results after the block has run. 
__block NSInteger foundIndex = NSNotFound; 

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    if ([obj isKindOfClass:[MyClass class]]) { 
     foundIndex = idx; 
     // stop the enumeration 
     *stop = YES; 
    } 
}]; 

if (foundIndex != NSNotFound) { 
    // You've found the first object of that class in the array 
} 

, 당신은 예를 조금 조정할해야 할 것이다, 그러나 이것은 당신이 무엇을 할 수 있는지 알려 주어야한다.

이 빠른 열거 형의 장점은 개체의 인덱스도 반환 할 수 있다는 것입니다. 또한 enumerateObjectsWithOptions:usingBlock:을 사용한 경우이 옵션을 동시에 검색 할 수 있으므로 스레드가있는 열거 형을 무료로 가져 오거나 역순으로 배열을 검색할지 여부를 선택할 수 있습니다.

블록 기반 API는보다 유연합니다. 새 것처럼 보이지만 복잡해 보이더라도 사용하기 시작하면 쉽게 이해할 수 있습니다. 그런 다음 어디에서나 사용할 수 있습니다.

+0

변수를 지정하여 열거를 중지하는 것 외에 블록 기반 방법을 사용할 때의 이점은 무엇입니까? – futureelite7

+0

-1 대신 NSNotFound를 사용합니다. – NSResponder

+0

@NSResponder - 좋은 캐치 - 고마워요. – Abizern

7

당신은 배열을 통해 루프로 빠른 열거를 사용하여 클래스를 확인할 수 있습니다 : 당신은뿐만 아니라이 작업을 수행하는 기반 열거 블록을 사용할 수

BOOL containsClass = NO; 

for (id object in array) { 
    if ([object isKindOfClass:[MyClass class]]) { 
     containsClass = YES; 
     break; 
    } 
} 
8

NSPredicate로이 작업을 수행 할 수 있습니다.

NSPredicate *p = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", 
                 [NSNumber class]]; 
NSArray *filtered = [identifiers filteredArrayUsingPredicate:p]; 
NSAssert(filtered.count == identifiers.count, 
     @"Identifiers can only contain NSNumbers."); 
관련 문제