为什么分配给这个NSMutableArray给EXC_BAD_ACCESS?我会出界吗?

问题描述:

我正在开发一款游戏,并且在init方法中,当我做[self loadGravityCenters]时,它会给出EXC_BAD_ACCESS。下面是该方法的定义:为什么分配给这个NSMutableArray给EXC_BAD_ACCESS?我会出界吗?

-(void) loadGravityCenters { 

    //These P1, P2, etc. are for seeing where the EXC_BAD_ACCESS is in the method. 
    printf("P1\n"); 
    //Get and open the file with coordinates 
    NSString *filePath = [[NSBundle mainBundle] pathForResource: @"gravitycenter" ofType: @"ballpoint"]; 
    FILE *fileHandle = fopen([filePath cStringUsingEncoding:NSASCIIStringEncoding],"r"); 
    //First array for storing the coordinates from the file. 
    NSMutableArray *coord; 
    //Vanilla C doesn't have an NSMutableArray, use tempCoord to place it in the NSMutableArray. 
    int tempCoord; 
    //i is used to keep track of where to assign stuff in coord). 
    int i = 0; 
    while (!feof(fileHandle)) { //Read file. 
     //Next check point. 
     printf("P2\n"); 
     //Assign tempCoord a number from file. 
     fscanf(fileHandle, "%d", &tempCoord); 
     //Convert the integer to NSNumber (so I can put it in coord. 
     NSNumber *intToNSNumber = [NSNumber numberWithInt:tempCoord]; 
     [coord insertObject:intToNSNumber atIndex:i]; 
     i++; 
    } 
    for (int j = 0; j < [coord count]; j+=2) { //Make the coord array into an array of CGPoints 
     printf("P3\n"); //Check point. 
     //Assign a gravityCenters (declared in header) a series of points. 
     [gravityCenters addObject:[NSValue valueWithCGPoint:CGPointMake([[coord objectAtIndex:j] floatValue], [[coord objectAtIndex:j+1] floatValue])]]; 
    } 

    for (int j = 0; j < [gravityCenters count]; j++) { 
     printf("P4\n"); //Last checkpoint. 
     //gravityWells (declared in header) is used to store CCSprites, make a bunch of sprites with the positions stored in gravityCenters. 
     [gravityWells addObject:[CCSprite spriteWithFile:@"GravityCenter.png"]]; 
     [[gravityWells objectAtIndex:j] setPosition:[[gravityCenters objectAtIndex:j] CGPointValue]]; 
     printf("gravityWell=%f,%f\n", ((CCSprite *)[gravityWells objectAtIndex:j]).position.x, ((CCSprite *)[gravityWells objectAtIndex:j]).position.y); 
     [self addChild:[gravityWells objectAtIndex:j]]; 
    } 
} 

总结:

让intgers阵列存储的坐标。转换它,以便它可以放置在一个CGPoint数组中。制作一堆CCSprites并给它们从CGPoint填充的数组中获得坐标。

文件我使用看起来像这样:

70 100 
80 89 
46 545 

程序在检查点P3失败。我试着更换行:

for (int j = 0; j < [gravityCenters count]; j++) { 

有了:

for (int j = 0; j < [coord count]-2; j+=2) { 
    //And: 
    for (int j = 0; j < [coord count]-3; j+=2) { 

想知道它只是一个越界-事情。但做我以上所做的事似乎并没有改变任何事情。任何帮助将不胜感激。

您需要先分配数组,然后才能使用它。试试:

NSMutableArray *coord = [[NSMutableArray alloc] init]; 

希望有所帮助!

+0

嗯,这算出EXC_BAD_ACCESS,我的精灵不显示......但首先是第一件事。谢谢! – Dair

+0

你确定你的精灵分配得当吗?此外,重力井和重力中心是否正确分配? – msgambel

+0

我相信,我正在为.h文件中的所有数组执行'@property(nonatomic,retain)'和'@ synthesize'。 – Dair