应用程序一个线程运行异步时iphone应用程序崩溃

时间:2010-10-23 15:25:47

标签: iphone

嗨,iam目前在iphone中的小型聊天应用程序中工作iam调用Web服务。一个用于数据发送,另一个用于获取朋友的响应,因此iam impelment代码如下。

NSMutableData *webData;
 NSXMLParser *xmlParser;
 NSMutableString *xmlParsingResult;
 NStimer *timer;
-(IBAction)send:(id)sender
{
 //req include web request info
 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
  if (conn) 
  {
   webData = [[NSMutableData data] retain];
  }
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
 [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [webData appendData:data]; 
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
 [connection release];
 [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
 xmlParser = [[NSXMLParser alloc] initWithData: webData];
 [xmlParser setDelegate: self];
 [xmlParser setShouldResolveExternalEntities: YES];
 [xmlParser parse]; 
 [xmlParser release];
 [connection release];
 [webData release];
}

-(void)parser:(NSXMLParser *)xmlparser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName   attributes: (NSDictionary *)attributeDict
{
 if( [elementName isEqualToString:@"string"])
 {
  if(!xmlParsingResult)
  {
   xmlParsingResult = [[NSMutableString alloc] init] ;
  }  
 } 
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
 [xmlParsingResult appendString: string]; 
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
 if( [elementName isEqualToString:@"string"])
 {
  if(timer!=nil)
  {    
  }
  else
  {
 [self performSelectorInBackground:@selector(CallResponse) withObject:nil];
  }
  xmlParsingResult=nil;
  [xmlParsingResult release];
 } 
} 
//==================================================================================================================
-(void)CallResponse
{
 NSLog(@"timer start:");
 NSAutoreleasePool *timerNSPool = [[NSAutoreleasePool alloc] init];
 timer = [NSTimer scheduledTimerWithTimeInterval:10.0  target:self selector:@selector(Refresh:) userInfo:nil repeats: YES]; 
 NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
 [runLoop run];
 [timerNSPool release];
}
-(void)Refresh:(NSTimer *)TimeVal
{
// call web service to get response 
// if error occur then timer will be release and nil
}

我的应用程序崩溃并且抛出了以下错误

bool _WebTryThreadLock(bool), 0x7089e20: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

plz代码plz给我帮助或代码snnipet 提前谢谢

1 个答案:

答案 0 :(得分:1)

错误消息可以准确地告诉您问题所在。对于它的价值,没有必要创建一个后台线程并运行循环只是为了启动NSTimer。您也可以在主线程中创建NSTimer - 它不会阻止它,它只会坐在运行循环中并在需要时触发。不需要-performSelectorInBackground:withObject: