NSMutableArray EXC_BAD_ACCESS when i try read from it
I want update position of Particles for store this information I use NSMutableArray. I want do update 1 time per 2 s开发者_如何学JAVAeconds for example. For this I try use this code.
//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];
}
But when i run it on first calling function and reading from particlesCoordinates array i have console message : Program received signal: "EXC_BAD_ACCESS". How I can make normal-working schedule?
[NSMutableArray arrayWithCapacity:5]
returns an autoreleased instance, and that gets cleaned up some time after leaving the initializer. Now the pointer partilesCoordinates
points to undefined memory. You need to do:
partilesCoordinates = [[NSMutableArray arrayWithCapacity:5] retain];
or
partilesCoordinates = [[NSMutableArray alloc] initWithCapacity:5];
Change this:
@property (assign, readwrite) NSMutableArray *partilesCoordinates;
to this:
@property (nonatomic, retain) NSMutableArray *partilesCoordinates;
and change this:
partilesCoordinates = [NSMutableArray arrayWithCapacity:5];
to:
self.partilesCoordinates = [NSMutableArray arrayWithCapacity:5];
When you synthesize a setter for an "assign" property, the accessor won't retain the value you pass it.
精彩评论