How to handle freezing programm at loading xml from bad url?

☆樱花仙子☆ 提交于 2020-01-17 07:55:28

问题


I want to handle freezing my program, when it load an xml from bad address. I tryed it with using @try and @catch, but it doesn't work. Can I use some alternative handling?

@try{
    NSString *test=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@",addressLabel.text,portLabel.text]] encoding:NSUTF8StringEncoding error: nil];
}

@catch (NSException *ex) {
    NSLog(@"Bad IP address");
    return;
}

回答1:


Run your XML Parser in NSThread and use notification for errors.




回答2:


initWithContentsOfURL is a synchronous call. The control will return back from the function only on complete. Try this function is a worker thread so that your main thread will not be blocked.




回答3:


If you use use NSThread then you have to dive into the memory management unless you are working in XCode 4.2 and using ARC.

So there are two ways for fetching the XML from the server.

1) Use NSURLConnection to get the xml as a NSData object and when you finish loading the data you can simply use that data to initialize an NSString Object. NSURLConnection sends asynchronous call to the server so it will not freeze your view.

2) You can use NSIncovationOperation and NSQueue to fetch your XML and it will also not effect your main thread. like

-(void)myMethod{
NSString *test=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@",addressLabel.text,portLabel.text]] encoding:NSUTF8StringEncoding error: nil];
    [self performSelectorOnMainThread:@selector(handleString:) withObject:test];
}

You can use NSInvocationOperation object as follow

 NSInvocationOperation *opr = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myMethod) object:nil];
    NSOperationQueue *queue= [NSOperationQueue new];
    [queue addOperation:opr];

When the perform selector will be call then you can pass that XML string object to the handleString: method. like

-(void)handleString:(NSString*)xmlString{
// Do something with string
}

I hope that it clarifies a little bit of your confusion. All this was to give you an idea how can you achieve your goal without freezing your interface i.e main thread.

regards,

Arslan




回答4:


You need to launch all long time operations on a second thread to avoid blocking the main thread. Use [self performSelector:@selector(yourXmlDownloadMethod)].



来源:https://stackoverflow.com/questions/8209583/how-to-handle-freezing-programm-at-loading-xml-from-bad-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!