views:

187

answers:

2

Hello everybody, 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 code 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.

A: 

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 ];
Macmade
Hello and thank you for your answer. I have tried to do as suggested, the newly created method sets the request, the connection and the pool. It is regularly called within a new thread as I can see from the console, but then nothing happens. I mean the delegate connection methods don't get called. No data appended, no connection success or failure. Any idea about that?
A: 

You will get your response here: http://www.wimhaanstra.com/2009/02/20/nsurlconnection-in-its-own-thread/

ecaste

ecaste