循环中的循环?

时间:2011-02-08 16:02:59

标签: iphone loops for-loop cocos2d-iphone nsmutablearray

我有两个可变数组,当我从索引更改的数组中删除对象时,我正在循环,我需要'rpoint'值和'rsprite'值在循环并重复代码时减少一个。 / p>

这是我到目前为止所拥有的东西。

    CGPoint cg1 = CGPointMake(33,33);
    NSValue *cg1obj = [NSValue valueWithCGPoint:cg1];

    CGPoint cg2 = CGPointMake(33,97);
    NSValue *cg2obj = [NSValue valueWithCGPoint:cg2];

    NSMutableArray *numberxy = [[NSMutableArray alloc] initWithCapacity:2]; int pointcount = 0;
    [numberxy insertObject:cg1obj atIndex:pointcount++];
    [numberxy insertObject:cg2obj atIndex:pointcount++];

    CGPoint red1point = CGPointMake(red1.position.x,red1.position.y);
    NSValue *red1pointobj = [NSValue valueWithCGPoint:red1point];

    CGPoint red2point = CGPointMake(red2.position.x,red2.position.y);
    NSValue *red2pointobj = [NSValue valueWithCGPoint:red2point];

    NSMutableArray  *sprites = [[NSMutableArray alloc] initWithCapacity:2]; int spritecount = 0;
    [sprites insertObject:red1pointobj atIndex:spritecount++];
    [sprites insertObject:red2pointobj atIndex:spritecount++];



    for (int i=0; i<3;i++) {
        int rpoint;
        int rsprite;

        do{
            rpoint = arc4random() % 2;
        rsprite = arc4random() % 2;
        } while (rpoint == 0 && rsprite == 0);

        CGPoint point = [[numberxy objectAtIndex:rpoint] CGPointValue];

        CGPoint sprite = [[sprites objectAtIndex:rsprite] CGPointValue];

        sprite = ccp(point.x,point.y);
        CCSprite *sprite1;

        if (rsprite <3) {
            sprite1 = [CCSprite spriteWithFile:@"Red tile.png"];
            sprite1.position = sprite;
            sprite1.scale = 0.9;
            [self addChild:sprite1];
        }
    }

但是一旦我将它添加到for循环中它就不起作用了,我意识到索引号在被删除时正在改变数组中的对象,因此为整数rpoint生成随机数的范围和rsprite(用于获取随机索引号)需要在代码重复时减一,但我不确定你是如何做到的。

if (sprite1.position.x == point.x && sprite1.position.y == point.y) {
            [numberxy removeObjectAtIndex:rpoint];
            [sprites removeObjectAtIndex:rsprite];
        }

2 个答案:

答案 0 :(得分:1)

在迭代过程中删除数组中的项目是一个非常糟糕的主意。

您可以做的事情的建议是维护另一个“要删除的项目”(最好是实际存储的对象指针,而不是索引),然后当您确定要从中删除的所有对象时数组,你迭代这个“要删除的项目”列表,找到主数组中的每个对象然后删除它。

答案 1 :(得分:0)

你可以根据数组中的对象数得到随机数,如下所示:

do{            
    rpoint = arc4random() % [numberxy count];
    rsprite = arc4random() % [sprites count];
} while (rpoint == 0 && rsprite == 0);
相关问题