Earl Grey
Earl Grey

Reputation: 7466

Parsing on B-thread but values to main thread?

I am very new to threading. Here's my problem. I have a custom Parser class, which uses NSXMLParser and also does some other minor things. It parses a XML from the network and creates a dictionary of values. I also have a DataProcesor helper class which processes the data (NSDictionary) that is passed to it from Parser and creates real CoreData objects from it in a managed context.

Now I want to move my Parser to a background thread. How would I do it? (NSthread, NSOperation, GCD...)? How should the Parser return those NSDictionaries to the Data Processor that is on the main thread?

The Parser object conforms to NSXMLParserDelegate protocol ie. it procesess the callbacks from NSXMLParser which the Parser owns.

Upvotes: 0

Views: 165

Answers (1)

bgolson
bgolson

Reputation: 3500

Use GCD to start up the XML Parser on a background thread

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    //call your xml parser
    //pass yourself in as it's delegate
});

When you receive the NSDictionary in your callback, jump back to the main queue before updating any UI elements

-(void)myCallBack:(NSDictionary*)newData {
    dispatch_async(dispatch_get_main_queue(), ^{
        //execute on main queue
        ProcessDictionaryData(newData);
    });
}

Upvotes: 1

Related Questions