【问题标题】:Iterating through children of a layer in cocos2d在 cocos2d 中遍历层的子节点
【发布时间】:2012-11-26 20:17:55
【问题描述】:

我正在尝试遍历并删除我的图层 (HUDLayer) 的所有子图层。我正在尝试通过以下方式完成这项任务:

    for(id *item in HUDLayer.children_)
    {
        [self removeChild:item cleanup:YES];
    }

但我得到一个错误 -> 表达式没有有效的对象类型

有人能解释一下我的问题吗?

谢谢

【问题讨论】:

    标签: iphone objective-c cocos2d-iphone


    【解决方案1】:
    for(id *item
    

    哎呀。 id 本身就是一个对象(也是一个指针),不需要星号。

    for(id item in HUDLayer._children)
    

    应该没问题。

    【讨论】:

    • 我知道它必须像这样简单。但是,现在它说对象“HUDLayer”没有属性 children_
    • @Joey 不是我的错 - 请参阅 HUDLayer 的文档。
    • children_ 是 CCNode 的属性,在 HUDLayer 中没有声明。它是否有理由无法从 CCNode 识别此属性?
    • @Joey HUDLayerCCNode 的实例吗?
    • 不,是CCLayer,但CCLayer是CCNode的子类
    【解决方案2】:

    在为另一个问题做了一些谷歌搜索后,才找到了这个。

    您正在尝试从父级 (HUDLayer) 中移除对象。其他人已经回答了“自我”的问题。不过……

    你说...

    for(id *item in HUDLayer.children_) {
        [self removeChild:item cleanup:YES];
    }
    

    ...但我虽然我会添加下面的代码,因为我认为它可能会帮助其他人尝试删除子节点而不发生循环突变。

    for(id item in HUDLayer.children) {
        // If it's a sprite that you want to remove
        if ([item isKindOfClass:[CCSprite class]]) {
            // Use this to remove or else you'll have a loop mutation.
            [item removeFromParentAndCleanup:YES];
        }
    }
    

    无论如何,希望它对某人有所帮助。

    大声笑 - 现在编辑这个,因为我(估计)迭代并从中删除,即使,父级可能会导致数组突变。所以,我正在修改上面的内容,首先将所有子元素放在一个数组中,然后我将遍历 IN REVERSE 并在此基础上删除对象。这样,避免了数组突变。见下文:

    NSArray *items = [[NSArray alloc] initWithArray: HUDLayer.children];
    
    for (long i = items.count - 1; i >= 0; i--) {
        id item = items[i];
        if ([item isKindOfClass:[CCSprite class]] ||
            [item removeFromParentAndCleanup:YES];
        }
    }
    
    items = nil;
    

    再次 - 希望它对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      相关资源
      最近更新 更多