下面是我的代碼包含一個線程。此線程照顧隊列大小,如果大小> 10,然後記錄並刪除最後一個對象。但是當我運行demo = [[myDemo alloc] init]啓動線程,並獲得異常消息=「EXC_BAD_ACCESS」。有沒有人幫我解決這個問題?NSThread崩潰[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(個體)訪問隊列
-(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;
}
如何聲明'q'? –
你用ARC嗎? –
@ Daij-Djan他沒有看到「[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]」 –