取消当前NSXMLParser解析操作的简便方法? [英] Easy way to cancel current NSXMLParser parsing operation?
问题描述
好的.
假设我有一个 UITextField
,用户可以在其中输入网址,例如:
Lets say i have a UITextField
where a user can input an url such as:
http://foo.bar/foo/bar.asmx
现在,如果为应用程序提供了正确的URL,它将使用 NSData
响应,其字节大小大约为450-700,具体取决于返回的值,用户之间的值有所不同.调用大约需要一秒钟左右的时间,而 NSXMLParser
也会在第二秒钟内解析数据.
Now, if the application is fed the right URL, it will respond with an NSData
with a bytesize of around 450-700 depending on the returning values, the values differ between users. The call takes around a second or so, and the NSXMLParser
parses the data within a second aswell.
但是只要我们输入例如:
But whenever we input for example:
http://apple.com/foo/bar.asmx
我们收到一个 NSData
,其字节大小约为9700.解析器通过无穷大解析此数据.而且我不知道当用户输入无效的URL并导致 NSXMLParser
解析为无穷大时,如何抛出正确的错误消息.
We recieve an NSData
with a bytesize of around 9700. And the parser parses this data through infinity. And i have no idea how to throw the proper errormessage when the user has made input to an invalid url resulting in the NSXMLParser
parses for infinity.
我们尝试使用它.
在
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
xmlParser = [[NSXMLParser alloc] initWithData:myData];
[xmlParser setDelegate:self];
[xmlParser shouldResolveExternalEntities:YES];
[xmlParser parse];
[self performSelector:@selector(timeOutMyParser:) withObject:nil afterdelay:15];
[xmlParser release];
[connection release];
[myData release];
}
现在,这段代码发生的事情是因为performSelector永远运行解析,所以它永远不会执行.
Now, what happens with this code is that the performSelector is never executed since it's forever running the parsing.
所以总结一下:
为了减少用户可以创建的错误的数量,如果需要花费很长时间,我们需要停止当前的NSXMLParser解析器操作.
In order to reduce the number of errors our users can create, we need to stop our current NSXMLParser parser operations if they take to long.
有什么简便的方法可以取消当前的解析操作?
Is there any EASY way to cancel the current parsing operation?
推荐答案
问题是 [xmlParser parse]
阻塞了主线程,从而锁定了所有线程.
The issue was that the [xmlParser parse]
was blocking the main thread, locking everything.
所以不是
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
xmlParser = [[NSXMLParser alloc] initWithData:myData];
[xmlParser setDelegate:self];
[xmlParser shouldResolveExternalEntities:YES];
[xmlParser parse];
[self performSelector:@selector(timeOutMyParser:) withObject:nil afterdelay:15];
[xmlParser release];
[connection release];
[myData release];
}
我这样做了.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
xmlParser = [[NSXMLParser alloc]init];
[xmlParser setDelegate:self];
[xmlParser shouldResolveExternalEntities:YES];
[self performSelectorInBackground:@selector(someFunction) withObject:xmlParser];
[xmlParser release];
[connection release];
[myData release];
}
其中 someFunction
是这样的.
-(void)someFunction:(NSXMLParser *)parser
{
parser = [[NSXMLParser alloc]initWithData:myData];
[parser setDelegate:self];
[parser parse];
[parser release];
}
这篇关于取消当前NSXMLParser解析操作的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!