2014-06-11 188 views
0
-(id) init 
    { 
     if((self=[super init])) { 
     _targets = [[NSMutableArray alloc] init]; 
     temp = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4",nil]; 
     tempArray = [[NSMutableArray alloc] initWithArray:temp]; 
     resultArray = [[NSMutableArray alloc] init]; 
     [self thelogic]; 
     } 
    return self; 
    } 

    -(void)thelogic 
    { 
     int i; 
     int count = 4; 
     for (i = 0; i < 3; i ++) { 
     int index = arc4random() % (count - i); 
     [resultArray addObject:[tempArray objectAtIndex:index]]; 
     CCSprite *target = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@.png", [tempArray objectAtIndex:index]]]; 
     target.tag = [[NSString stringWithFormat:@"%@",[tempArray objectAtIndex:index]] integerValue]; 
     [self addChild:target]; 
     [_targets addObject:target]; 
     [tempArray removeObjectAtIndex:index]; 
    } 
    } 

    -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
     [_targets removeAllObjects]; 
     [self thelogic]; 
    } 

从上行代码,我得到三个不同的数字,他们提出三点精灵不同的图像时,进入这个场景,我想触摸屏,三个老精灵将被删除,并三个新的精灵会显示,但上面的代码总是崩溃,所以我该如何解决它?感谢错误索引超出范围

+0

请发布应用程序崩溃时得到的确切错误消息... – sergio

+0

@sergio错误消息是*** - [__ NSArrayM objectAtIndex:]:index 3 beyond bounds [0 .. 0]',谢谢 – matt

回答

1

这是很难理解你正在尝试在theLogic方法去做,但我会建议你更换

int index = arc4random() % (count - i); 

int index = arc4random() % [tempArray count]; 

这将修复崩溃,但我怀疑你的程序会按预期工作。事实上,你只在init方法中填充tempArray;第一次调用theLogic将删除其所有元素,并据我看到该阵列不再被填充。所以,当你调用ccTouchesBegan然后调用theLogic时,tempArray将为空。

对不起,如果我缺少任何点。

+0

in 'thelogic',我尝试添加三个精灵,每个精灵都有不同的标记和不同的图像。 – matt

+0

@DMusic:感谢您的评论。你能否检查一下我的关于'index'的建议是否可以修复崩溃? – sergio