2011-09-06 128 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."); 
相关问题