【问题标题】:How to check if an NSArray contains an object of a particular class?如何检查 NSArray 是否包含特定类的对象?
【发布时间】:2011-09-06 00:47:13
【问题描述】:

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

【问题讨论】:

    标签: objective-c nsarray


    【解决方案1】:

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

    // 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 更加灵活。尽管它们看起来既新又复杂,但一旦您开始使用它们就很容易上手 - 然后您就会开始看到在任何地方使用它们的机会。

    【讨论】:

    • 使用基于块的方法除了可以指定一个变量来停止枚举之外还有什么好处?
    • 我会使用 NSNotFound 而不是 -1。
    • @futureelite:块调用比 Objective-C 方法调用更快。
    【解决方案2】:

    您可以使用 NSPredicate 来做到这一点。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-03-15
        • 2018-11-02
        • 1970-01-01
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        • 2019-01-12
        • 1970-01-01
        相关资源
        最近更新 更多