How to execute an NSUrlConnection in a separated thread?
I am moving my first steps both with url connections and threads so bear with me if the question may result trivial. Basically I would like to execute an NSUrlConnection in a separate thread (even if this may result 'dangerous' as many documents state). Before deciding whether to adopt this solution or not I should manage to implement it first. Now the question is really simple: what is the actual cod开发者_如何转开发e for doing that. I know that
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
executes the download, I've tried it seems to work. I have read that
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
and
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
are to be used to create a new thread
Now, how to add the initWithRequest method to the thread? Both thread methods seem to accept a selector with at most one parameter. Reading the actual required code would be really appreciated.
Thank you.
You can create a method that will take care of the creation of the NSURLConnection, and other related stuff.
Then, call that method in another thread.
- ( void )connect
{
NSAutoreleasePool * pool = [ [ NSAutoreleasePool alloc ] init ];
NSURLConnection * theConnection = [ [ NSURLConnection alloc ] initWith ... ];
/* Rest of the code... */
[ pool release ];
}
The NSAutoreleasePool is needed to handle autoreleased objects. As the connect method is executed on a different thread, no pool is in place, and you have to create it yourself.
Then creates a thread for the connect method:
[ NSThread detachNewThreadSelector: @selector( connect ) toTarget: self withObject: nil ];
精彩评论