下面是我的代码包含一个线程。这个线程负责队列大小,如果大小> 10,则记录并删除最后一个对象。但是当我运行 demo=[[myDemo alloc]init] 启动线程时,并得到异常消息= “EXC_BAD_ACCESS”。有人帮我解决这个问题吗?
@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 和 popData 通过@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;
}