Steve Edwin
Steve Edwin

Reputation: 89

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.

Upvotes: 0

Views: 400

Answers (2)

cream-corn
cream-corn

Reputation: 1840

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

Upvotes: 1

jgoldbg
jgoldbg

Reputation: 53

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.

Upvotes: 1

Related Questions