Below is my code include a thread.This thread take care the queue size,if size > 10 then log and remove the last object.But when I run demo=[[myDemo alloc]init] to start thread,and get exception message="EXC_BAD_ACCESS".Have any guy help me to solve this problem?
@interface myDemo:NSObject
{
NSMutableArray *q;
NSThread *thread;
bool running;
}
-(void)putData:(NSData *)data;
-(NSData *)popData;
-(void)stopThread;
@end;
@implementation myDemo
-(id)init
{
if(NULL!=(self = [super init]))
{
q=[NSMutableArray array];
thread=[[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[thread start];
}
return self;
}
-(void)myThreadMainMethod:(id)object
{
unsigned long count;
NSData *data;
if(running) return;
running=true;
while(running)
{
@synchronized(self)
{
count=[q count];//crash !!!!
if(count>10)
{
data=[q lastObject];
NSLog(@"count=%d ,remove last data=%@",count,[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
[q removeLastObject];
}
}
}
running=false;
}
putData and popData are access the queue by @synchronized(self)
-(void)putData:(NSData *)data
{
@synchronized(self)
{
[q addObject:data];
}
}
-(NSData *)popData
{
NSData * data=NULL;
unsigned long count;
@synchronized(self)
{
count=[q count];
if(count!=0)
{
data=[q lastObject];
[q removeLastObject];
}
}
return data;
}