问题
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