I am currently working on an application which is parsing some JSON data in the APPdelegate class when the location is changed.
My question is: " How is the most appropriate way doing it ?" Currently when it is parsing the data the application is "frozen" until the data has been loaded.
I need some advice :)
Thanks
There are several ways of course, including NSThread, NSOperation and old-fashioned libpthread. But what I find the most convenient (especially for simple background tasks) is libdispatch also called Grand Central Dispatch.
Using dispatch queues you can quickly delegate a time-consuming task to a separate thread (or more precisely, execution queue - GCD decides whether it's a thread or an asynchronous task). Here's the simplest example:
// create a dispatch queue, first argument is a C string (note no "@"), second is always NULL
dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(jsonParsingQueue, ^{
[self doSomeJSONReadingAndParsing];
// once this is done, if you need to you can call
// some code on a main thread (delegates, notifications, UI updates...)
dispatch_async(dispatch_get_main_queue(), ^{
[self.viewController updateWithNewData];
});
});
// release the dispatch queue
dispatch_release(jsonParsingQueue);
The above code will read JSON data in a separate execution queue, not blocking the UI thread. This is just a simple example and there's a lot more to GCD, so take a look at the documentation for more info.
Use NSOperation to handle it.
You may follow this tutorial: http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
And apple document: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With