BlueDolphin
BlueDolphin

Reputation: 9765

Is there any sample code to do iPhone mulitithreading tasks?

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.

Upvotes: 1

Views: 1814

Answers (4)

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.

Upvotes: 1

wisequark
wisequark

Reputation: 3268

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).

Upvotes: 2

BobbyShaftoe
BobbyShaftoe

Reputation: 28499

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

Upvotes: 2

Ben Gottlieb
Ben Gottlieb

Reputation: 85542

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

Upvotes: 7

Related Questions