如何检查NSArray是否包含特定类的对象?

时间:2011-09-06 00:47:14

标签: objective-c nsarray

测试NSArray是否包含某种类型的对象的最佳方法是什么? containsObject:似乎在考验平等,而我正在寻找isKindOfClass:平等检查。

3 个答案:

答案 0 :(得分:26)

您也可以使用基于块的枚举来执行此操作。

// 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更灵活。虽然它们看起来既新又复杂,但一旦开始使用它们就很容易上手 - 然后你就会开始看到在各处使用它们的机会。

答案 1 :(得分:9)

您可以使用NSPredicate执行此操作。

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

答案 2 :(得分:7)

您可以使用快速枚举来遍历数组并检查类:

BOOL containsClass = NO;

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