Threaded programming in Objective-C, for sending request to a web server
I'm in this kind of situation... I want to patch 100 different web requests, but it's separated in three different functions:
-(void)functionMain {
for(int i = 0; i < 100; i++)
[self sendRequestToServer];
}
So that first function will basically send request to some URL and wait for it to finish...
-(void)sendRequestToServer {
[request sendRequest:mAddress];
[request didFinishSelector:@"refreshAddress"];
[request startAsynchronous];
}
This function above will do the actual sending of the address.
-(void)refreshAddress {
NSString *result = [requ开发者_JAVA百科est getResponse];
mAddress = [result getTheNextAddress];
[self refreshDisplay];
}
Now this will set mAddress to the next web address. So I got a lot of this, and apparently one request takes a bit of time (around 600 ms), but if you notice in the main loop in functionMain
, I don't have any mechanism to see whether refreshAddress
has finished doing its job, because it it hasn't then I'll only be sending request with the same address over and over.
I tried using a boolean variable to guard the loop, but it doesn't look like it's working... Is there any graceful way to do this? I'm not sure what should I look for.. I don't know if NSOperation
or NSThread
will help me.
EDIT: As I mentioned in the comment, this is probably more like I'm having a multi-threading situation here (to be exact this might be 100 threads) that I want to make into only a single thread.
EDIT: So what I really want is like this (suppose the loop is only 3):
functionMain(i = 0) ->
sendRequestToServer
Then we wait until that finishes, then we have this:
refreshAddress (mAddress has been set to something else now) ->
functionMain (i = 1) ->
sendRequestToServer
Once again:
refreshAddress (mAddress has been set to something else now) ->
functionMain (i = 2, finished)
Very very sorry if I can't describe the problem more clearly... I wish I can write better english and can describe things clearer!
Possibly I'm not following you here but if you want them to happen one after the other you should use a synchronous request in NSURLConnection.
+ sendSynchronousRequest:returningResponse:error:
精彩评论