Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dataWithContentsOfURL bad when launching the app?

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?

like image 746
Yep Avatar asked Nov 20 '11 04:11

Yep


2 Answers

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

like image 139
bryanmac Avatar answered Sep 26 '22 17:09

bryanmac


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.

like image 32
George Avatar answered Sep 26 '22 17:09

George