【发布时间】:2011-06-07 06:17:40
【问题描述】:
当我尝试访问正确加载的 NSMutable 数组时,我在运行时遇到了崩溃。 这是代码
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 的自动释放功能会不会是问题所在?
【问题讨论】:
-
@Krypton - 我认为情况并非如此。 Apple 文档说 [NSMutableArray array] 创建并返回一个空数组。我可能是错的,但我的印象是这做了必要的分配。
-
“标记为正确答案”在哪里?氪你是对的。
-
我会将其转发为答案 :) 乐于助人!
-
似乎有所不同。 NSMutableArray *array = [NSMutableArray 数组]; //创建一个空数组,我可以向其中添加对象。但是当从另一个函数调用数组时它会崩溃应用程序
-
如果你没有分配数组,那么它会在方法完成后自动释放,因为它有 autorelease 。见下面链接stackoverflow.com/questions/844188/…
标签: objective-c crash runtime nsmutablearray