Cocos2d在循环中添加子项:无法添加子项

时间:2012-06-15 15:19:19

标签: objective-c cocos2d-iphone

我是Objective-C和Cocos2d的新手,我真的不明白为什么我使用以下代码得到以下错误。你能帮忙吗?

- (NSArray *) menuItemsArray
{   
    NSMutableArray *array = [NSMutableArray alloc];
    for (Player * player in playersArray) {
        NSLog(@"creating menu item with image %@",player.imageFilename);
        CCLayer *newPage = [[CCLayer alloc] init];
        CCMenuItemImage *titem = [CCMenuItemImage itemFromNormalImage:player.imageFilename
                                                    selectedImage:player.imageFilename
                                                           target:self selector:@selector(playerSelected:)];

        CCMenu *menu = [CCMenu menuWithItems: titem, nil];
        menu.position = ccp(self.contentSize.width/2, self.contentSize.height/2);

        NSLog(@"before adding item to layer");
        //[titem removeFromParentWithCleanup:YES];
        [newPage addChild:titem];
        //[newPage release];
        NSLog(@"after adding item to layer");
        [array addObject:newPage];

        /*
        [titem release];*/
        //[newPage release];
        //[menu release];
    }    
return array;
}

我收到错误:

2012-06-15 17:13:11.003 Killer[3222:707] *** Assertion failure in -[CCLayer     addChild:z:tag:], /Users/max/Documents/workspace/Killer/Killer/libs/cocos2d/CCNode.m:388
2012-06-15 17:13:11.006 Killer[3222:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'child already added. It can't be added again'

很抱歉,如果这个问题的级别很低......谢谢你能帮助我! :)

1 个答案:

答案 0 :(得分:1)

您的错误是您尝试将创建的menuItem添加到两个父级。仅将其添加到菜单中。然后将菜单添加到图层。替换你的行

[newPage addChild:titem];

这一个

[newPage addChild:menu];

你将收到每个玩家的一系列页面。