2011-09-06 130 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

我會使用NSNotFound而不是-1。 – 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."); 
相關問題