NSMutableArray在运行时崩溃

问题描述:

当运行时试图访问正确加载的NSMutable数组时遇到了崩溃。 这里是代码NSMutableArray在运行时崩溃

NSMutableArray *gameItems; 

-(id) init 
{ 
     if((self=[super init])) { 

     //initialize array  
     gameItems = [NSMutableArray array]; 

     for(int i = 0; i < 3; i++) 
     { 
      GI *gameItem = [[GI alloc] init]; 
      gameItem.image = [[CCSprite alloc] initWithFile:@"triangle.png"]; 
      gameItem.Position = ccp(140+40*i,200); 
      [gameItems addObject:gameItem]; 
      [gameItem release]; 
      NSLog(@"%d",[gameItems count]); //SHOWS THE SIZE OF THE ARRAY INCREMENTING CORRECTLY 
     } 
     NSLog(@"%d",[gameItems count]); //show " 3 " correct ! 

     for(GI *gameItem in gameItems) 
     { 
      [self addChild:gameItem.image]; 
      NSLog(@"%d",[gameItems count]); //show 3 correct ! 
     } 
     [self schedule:@selector(callEveryFrame:)]; 
    } 
    return self; 
} 

- (void) callEveryFrame:(ccTime)dt 
{ 
    NSLog(@"----->%d",[gameItems count]); //CRASHES AT RUNTIME IN THIS LINE 
} 
@end 

请别人解释我为什么会这样。 NSMutableArray的自动释放功能可能是问题吗?

+0

你会得到什么错误? – csano 2011-06-07 06:24:32

+1

@Krypton - 我不认为这是事实。 Apple文档说[NSMutableArray数组]创建并返回一个空数组。我可能是错的,但我的印象是这样做了必要的分配。 – csano 2011-06-07 06:26:56

+0

“标记为正确答案”在哪里? 氪你是对的。 – HoNgOuRu 2011-06-07 06:29:41

(转贴收费)

如果阵列gameItems是一个成员,它似乎是,要能够访问它的其他功能,如callEveryFrame那么你一定需要以这种方式已经初始化它:gameItems = [[NSMutableArray alloc] init];

(你错过了我认为的分配)