简体   繁体   中英

XML Parser is blocking main thread

I have an XML Parser that when it starts it makes the whole app freeze until it is finished, I call the parser using:

xmlParser = [[XMLParser alloc] loadXMLByURL:@"http://abdelelrafa.com/test2.xml"];

What is the best way to have the XML parser work without disrupting the main thread? I want to know if using another thread is the best option, or using something else.

If you're going to use initWithContentsOfURL you definitely should do your work off of the main thread, and then pick back up on the main thread once you have the init result.

Depending on the size of your document, you may find it better to first get the contents of the URL as NSData using an NSURLConnection , which does its work without blocking the main thread, and then calling [XMLParser initWithData] once you have the data. This has the added benefit that you can actually deal with networking errors separately from XML errors.

Try using GCD to do this operation for you:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    xmlParser = [[XMLParser alloc] loadXMLByURL:@"http://abdelelrafa.com/test2.xml"];
    dispatch_async(dispatch_get_main_queue(), ^{
       // Update UI
    });
});

Enter a dispatch_async on a new queue, in this block do all tour network operations/xml parsing then create another dispatch_async this time on the main queue so you can update UI elements or callback for completion/failure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM