' NSInvalidArgumentException'当试图添加一个孩子

时间:2014-06-28 17:36:56

标签: sprite-kit

运行代码时出错。错误是;

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'尝试添加已有父级的SKNode:name:'(null)'texture:['topObstacle1'

我搜索了问题,但我找不到任何解决方案。我知道发生错误的行。 [self addChild:topObstacles [y]]是问题的根源。这是我的代码;

- (void)createObstacles
{
    // Calculate how many obstacles we need, the less the better
    nbObstacles = ceil(WIDTH(self)/(OBSTACLE_INTERVAL_SPACE));

    CGFloat lastBlockPos = 0;
    bottomObstacles = @[].mutableCopy;
    topObstacles = @[].mutableCopy;

    SKSpriteNode * topObstacle1 = [SKSpriteNode   spriteNodeWithImageNamed:@"topObstacle1"];
[topObstacles addObject:topObstacle1];

SKSpriteNode * topObstacle2 = [SKSpriteNode spriteNodeWithImageNamed:@"topObstacle2"];
[topObstacles addObject:topObstacle2];

SKSpriteNode * bottomObstacle1 = [SKSpriteNode spriteNodeWithImageNamed:@"bottomObstacle1"];
[bottomObstacles addObject:bottomObstacle1];

SKSpriteNode * bottomObstacle2 = [SKSpriteNode spriteNodeWithImageNamed:@"bottomObstacle2"];
[bottomObstacles addObject:bottomObstacle2];


for (int i=0;i<nbObstacles;i++) {

    int y = arc4random() % 2;
    [topObstacles[y] setAnchorPoint:CGPointZero];

    [self addChild:topObstacles[y]];

    int z = arc4random() % 2;
    [bottomObstacles[z] setAnchorPoint:CGPointZero];

    [self addChild:bottomObstacles[z]];

    }

那么,您对此有何看法?

1 个答案:

答案 0 :(得分:0)

你在for循环中选择一个随机数组索引,其中可以随机选择相同的索引(y),从而将相同的对象(比如索引1处的那个)添加两次:

// 1st iteration, y is 1:
int y = arc4random() % 2;
[self addChild:topObstacles[y]];

// 2nd iteration, y is randomly chosen to be 1 again:
int y = arc4random() % 2;
[self addChild:topObstacles[y]]; // BAM! This node has already been added...

要解决此问题,请选择另一个随机数,如果topObstacles[y].parent不是nil,或者只删除您使用[topObstacles removeObjectAtIndex:y]从数组中添加的节点 - 这需要topObstacles为NSMutableArray。