我的计时器并没有停止我的解析

问题描述:

我想放入一个超时,以防万一找到我的位置需要很长时间,发出相关的URL并解析xml。当我在locationManager中使用performSelector:withObject:afterDelay时(只是为了测试获取xml),它工作正常,但是当我在解析器周围放置类似的代码时,它实际上并不中止解析。我正在通过将延迟降至0.01来测试这一点。我的计时器并没有停止我的解析

我的问题是:即使将延迟设置为0.01,它仍然等待所有解析首先完成,然后才会放置在parsingDidTimeout方法中编码的alertView。

我没有尝试这与计时器,这是行不通的performSelector:在我的代码的其他部分。无论哪种方式,它不会放置alertView,并停止解析,直到解析完成后,无论需要多长时间。

我创建了一个需要半径的网址。首先我尝试一个小的半径,但如果我没有得到所需的数据,我扩大半径并再次发送URL并再次解析。这是我的StartParsing方法的一部分。

xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; 
XMLParser *parser = [[XMLParser alloc] initXMLParser]; 
[xmlParser setDelegate:parser]; 

if (!hadToExpandRadius){//meaning, only do this the first time I send out the url and parse 
[self performSelector:@selector(parsingDidTimeout:) withObject:nil afterDelay:0.01]; 
} 
//Start parsing the XML file. 
BOOL success = [xmlParser parse]; 

if(success){ 
if((didNotGetTheDataYet) && (radius < 500)){ 
hadToExpandRadius = YES; 
radius = radius + 35; 
[self startParsing];//do this same method, with larger radius 
} 
else { 
NSLog(@"No Errors"); 
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(parsingDidTimeout:) object:nil];} 
[parser release]; 
} 

-(void)parsingDidTimeout{ 
     [xmlParser abortParsing]; 
    UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Try Later" message:@"We need a better connection. We can get the data later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [servicesDisabledAlert show]; 
    [servicesDisabledAlert release]; 
    [myActivityView stopAnimating]; 

}

谢谢您的帮助。

调用performSelector:withObject:afterDelay:您要求运行循环稍后调用选择器。但是[xmlParser parse]会阻止运行循环,所以它没有机会叫你选择器。

abortParsing被设计为在解析器的委托方法中被调用。

解决方法可以在单独的线程中解析。

+0

现在我有'[self performSelector:@selector(parsingDidTimeout :) withObject:nil afterDelay:2];'然后'[self performSelectorInBackground:@selector(backgroundParse)withObject:nil]'。然后backgroundParse调用'[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(parsingDidTimeout :) object:nil];'当它成功时。现在我的问题是,当超时发生时,它调用parsingDidTimeout,我得到一个无法识别的选择器错误。我目前有'\t [xmlParser abortParsing];'在parsingDidTimeout中,但即使这样,我得到的错误。啊。怎么办?谢谢! – snorkelt 2010-10-31 19:53:01

+0

似乎只是一个错字。在@selector(parsingDidTimeout :)中有一个':',但该方法被声明为空。 – Yuras 2010-10-31 20:19:48

+0

我从我的parsingDidTimeout方法调用[xmlParser abortParsing]。我如何从我的委托方法中调用它?这是在不同的线程,但我需要从我的主线程调用parsingDidTimeout。它仍然不会中止解析,即使alertView弹出。 – snorkelt 2010-10-31 20:32:08

发现它 - 只是额外的“:”在我的performSelector:@selector(parsingDidTimeout :)! 我认为这是与第二个线程有关的东西。只是语法。

感谢您解释阻止运行循环的解析。我希望不需要另一个线程,但你的建议解决了我的问题。谢谢。