I make an app that accesses some data on the first launch and then displays it. I've been downloading this data this way:
NSData *data = [NSData dataWithContentsOfURL:url];
Is this bad? Right now I've set the method that contains this to run in a background thread using GCD, but I heard that since dataWithContentsOfURL
is synchronous, it's bad. Are there any opinions on this?
It's bad if you run it on the main UI thread. That will block the responsiveness of your app which is bad but it's even worse on start up.
You need to make it async. You can do that by either running that method on a background thread (GCD dispatch_async) or by using async methods of NSUrlConnection.
Here's an example of using GCD to work in the background and then update the UI (after done) on the main thread:
GCD, Threads, Program Flow and UI Updating
Another option is async method of NSUrlConnection. See the initWithRequest methods here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
You're safe as long as you're running it in a background thread.
The idea that synchronous loading is bad is only valid for the main UI thread. A long running operation on the main UI thread will make your app unresponsive. Doing it in the background is the correct way to do this. Also, consider using:
+dataWithContentsOfURL:options:error:
so that you can get an error back if anything goes wrong.
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