当我尝试从它读取时,NSMutableArray EXC_BAD_ACCESS

时间:2010-10-19 09:48:29

标签: objective-c cocos2d-iphone schedule

我想要粒子的更新位置来存储我使用NSMutableArray的信息。我希望每2秒更新一次,例如。为此,我尝试使用此代码。

//ParticlesLayer.h
@interface ParticlesLayer : CCLayer {
CCQuadParticleSystem *particle;
NSMutableArray *partilesCoordinates;
}

@property (assign, readwrite) NSMutableArray *partilesCoordinates;
-(void)partilesMove:(ccTime)dt;
-(void)particleInit;

//ParticlesLayer.m
@implementation ParticlesLayer

@synthesize partilesCoordinates;

-(id) init {
self = [super init];
    partilesCoordinates = [NSMutableArray arrayWithCapacity:5];
    [partilesCoordinates addObject: [NSValue valueWithCGPoint:ccp(67,152)]];
    [partilesCoordinates addObject: [NSValue valueWithCGPoint:ccp(140,147)]];
    [partilesCoordinates addObject: [NSValue valueWithCGPoint:ccp(198,100)]];
    [partilesCoordinates addObject: [NSValue valueWithCGPoint:ccp(261,126)]];
    [partilesCoordinates addObject: [NSValue valueWithCGPoint:ccp(364,135)]];
    // bla bla bla
    //...
    //bla bla bla
    [self schedule:@selector(partilesMove:) interval:2];
    return self;
} 

-(void)emittersMove:(ccTime)dt{
    NSMutableArray *newParticlesCoordinates = [NSMutableArray arrayWithCapacity:5];
    CGPoint newPoint;
    for (int i = 0; i < 5; ++i) {
        [self particleInit];
        NSLog(@"%@", [particlesCoordinates objectAtIndex:i]); // on this part of code i have problem
        particle.position = [[particlesCoordinates objectAtIndex:i] CGPointValue];
        [self addChild:emitter];
        newPoint = emitter.position;
        newPoint.x += 15;
        newPoint.y += 15;
        [newParticlesCoordinates addObject:[NSValue valueWithCGPoint:newPoint]];
    }
    [partilesCoordinates removeAllObjects];
    [partilesCoordinates newParticlesCoordinates];
    [newParticlesCoordinates removeAllObjects];
}

但是当我在第一次调用函数和从粒子坐标数组中读取它时,我有控制台消息:程序接收信号:“EXC_BAD_ACCESS”。我怎样才能正常工作?

2 个答案:

答案 0 :(得分:3)

[NSMutableArray arrayWithCapacity:5]返回一个自动释放的实例,并在离开初始化程序后一段时间清理。现在指针partilesCoordinates指向未定义的内存。你需要这样做:

partilesCoordinates = [[NSMutableArray arrayWithCapacity:5] retain];

partilesCoordinates = [[NSMutableArray alloc] initWithCapacity:5];

答案 1 :(得分:2)

改变这个:

@property (assign, readwrite) NSMutableArray *partilesCoordinates;

到此:

@property (nonatomic, retain) NSMutableArray *partilesCoordinates;

并改变这一点:

partilesCoordinates = [NSMutableArray arrayWithCapacity:5];

为:

self.partilesCoordinates = [NSMutableArray arrayWithCapacity:5];

当您为“assign”属性合成setter时,访问者将不会保留您传递它的值。