【问题标题】:Count number of CCNodes of a certain class on a layer统计某一层某类的CCNode个数
【发布时间】:2014-03-30 00:06:56
【问题描述】:

很简单的问题。我正在使用Objective C(cocos2d),我正在尝试计算当前显示的图层上存在的某个类的精灵的数量。例如,我有一个名为Seal 的类,它是CCNode 的子类,在我当前的层中,我想计算存在多少Seal 类型的实例。

我知道如何通过做来计算图层的子层数

int numberChildren = [[self children] count];

正确返回层上的子节点数。但我只想要我层上Seals 的数量。我怎么能这样做?谢谢=)

【问题讨论】:

    标签: ios objective-c xcode cocos2d-iphone


    【解决方案1】:

    您可以使用谓词函数来做到这一点,例如:

    NSArray * nodes = [self children];
    
    NSIndexSet * sealSet = [nodes indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
    {
        return [obj isKindOfClass:[Seal class]];
    }];
    
    NSArray * sealArray = [nodes objectsAtIndexes:sealSet];
    NSUInteger numberOfSeals = [sealArray count];
    

    编辑: 实际上你不必将印章存储在一个新的数组中,你可以简单地计算它们:

    NSUInteger numberOfSeals = [sealSet count];
    

    【讨论】:

      【解决方案2】:

      您可以尝试下面的代码,它不使用数组,因此内存占用更少--

      NSInteger sealCounter = 0;
      for(id item in [self children])     
           if([item isKindOfClass:[Seal class])
               sealCounter++; //After the for loop ends you can know how many Seals you have
      

      但是,如果您想在对 Seals 进行计数后仅对它们运行一些操作,那么将这些项目存储在数组中会帮助您:

      NSMutableArray *sealArray;
      for(id item in [self children])     
           if([item isKindOfClass:[Seal class])
               [sealArray addObject:(Seal *)item];//This will hold only seals and you can get the count by simply doing [sealArray count];
      

      【讨论】:

        猜你喜欢
        • 2022-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-16
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        相关资源
        最近更新 更多