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

Dan*_*Dan 18 objective-c nsarray

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

Abi*_*ern 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
}
Run Code Online (Sandbox Code Playgroud)

如果你的数组中有这种类的多个对象,你将不得不稍微调整一下这个例子,但是这应该会让你知道你可以做些什么.

这种快速枚举的一个优点是它允许您还返回对象的索引.此外,如果您使用过,enumerateObjectsWithOptions:usingBlock:您可以设置选项以同时搜索它,因此您可以免费获得线程枚举,或者选择是否反向搜索数组.

基于块的API更灵活.虽然它们看起来又新又复杂,但一旦开始使用它们就很容易上手 - 然后你开始看到各处都有机会使用它们.

  • @futureelite:块调用比Objective-C方法调用快. (3认同)

Ona*_*ato 10

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

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


fut*_*te7 7

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

BOOL containsClass = NO;

for (id object in array) {
    if ([object isKindOfClass:[MyClass class]]) {
         containsClass = YES;
         break;
    }
}
Run Code Online (Sandbox Code Playgroud)