views:

1106

answers:

4

I have some slow internet task to save and load file, I'd like to do those slow tasks in some background thread. I am wondering whether that's doable, and if it is, any sample code?

Then after it is finished, I'd like it to notice back to the main thread, so that I could update the UI.

Thanks in advance.

// Jack

+7  A: 

Take a look at NSURLConnection. It will load an NSURL (using NSURLRequest) in the background, and send delegate methods regarding its status.

Ben Gottlieb
+2  A: 

Log in to the iPhone Developer Center and search for Introduction to Threading Programming. Or, maybe you can log in and use this link:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Multithreading/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/10000057i-CH1-SW1

BobbyShaftoe
+2  A: 

Ultimately the device you are running your code on has a single processor and cannot possibly load large quantities (gigabytes) of data. The best route, by is likely that suggested by Ben (NSURLConnection asynchronously) which gives you the added advantage of being able to cleanly cancel and handle error messages. While it isn't technically threaded in the way you probably think you want it to be, it is well integrated with the event loop and is non-blocking. If that is still not enough, I would suggest looking at NSOperation and NSOperationQueue. You can fire off an NSOperation sub-class object and perform the download there (I would still advise doing it asynchronously there so as to enable canceling, pausing, etc).

wisequark
+1  A: 

If you do decide you need a background thread even after using asynchronous HTTP calls to gather the data, don't forget to wrap the background thread code in a new NSAutoReelasePool and then release it at the end.

Kendall Helmstetter Gelner
In one of my program, I did that way, use asynchronous HTTP and background thread, which improves performance, but I am wondering why I need background thread after I uses NSURLConnection.
BlueDolphin