2010-10-19 99 views
1

我想要更新位置的粒子存儲此信息我使用NSMutableArray。例如,我想每2秒更新一次。爲此我嘗試使用此代碼。NSMutableArray EXC_BAD_ACCESS當我嘗試從它讀取

//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]; 
} 

但是,當我在第一次調用函數運行它,並從particlesCoordinates陣列讀取我有控制檯消息:程序接收到的信號:「EXC_BAD_ACCESS」。我如何制定正常工作時間表?

回答

3

[NSMutableArray arrayWithCapacity:5]返回一個自動釋放實例,並在離開初始化程序一段時間後得到清理。現在指針partilesCoordinates指向未定義的內存。你需要做的:

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

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

謝謝這是非常好的工作 – Mike 2010-10-19 10:08:05

2

更改此:

@property (assign, readwrite) NSMutableArray *partilesCoordinates; 

這樣:

@property (nonatomic, retain) NSMutableArray *partilesCoordinates; 

並改變這一點:

partilesCoordinates = [NSMutableArray arrayWithCapacity:5]; 

到:

self.partilesCoordinates = [NSMutableArray arrayWithCapacity:5]; 

當您爲「分配」屬性合成一個setter時,訪問器不會保留您傳遞它的值。

+0

良好的漁獲,沒有看到他使用屬性,因此也錯過了他的錯誤聲明。 – DarkDust 2010-10-19 10:01:01

相關問題