开发者

How to synchronise callback function when in a loop

I am pretty new to iPhone development. i need some help on how to synchronize a callback method and a for loop.

For example: I have a for loop say 1 to 3.

Within this loop, first i send message to a receiver. The result from the receiver is obtained in a callback function. With this result i need to perform some parsing. Now how can i continue with the loop??

BR, Suppi

Edited with Code:

-(void)requestData{

for (int i=1; i<3; i++) {

    completeMessage = [self generateMessage:message];
    [self sendMessageT开发者_运维问答oReceiver:completeMessage];
 //now it goes to the callback function to read message from receiver. How do i return to this point?? to continue the loop.
    [self dosomething:result];

}

  }


I don't know much about iPhone development but based on my asynchronous function calling experience you might have to reconsider your approach - assuming this is an asynchronous function call.

When you go through the loop the first time, your code is going to call all the asynchronous functions and move on. It is not going to wait. If you want it to wait for each function call then you either shouldn't use asynchronous functions or use a thread.wait or thread.sleep function in the loop. You could also use some kind of thread synchronization and signalling in the loop. For example, you could make the asynchronous call and then your thread waits until it gets a signal from your callback to continue.

You may want to take your custom end processing out of the loop and do it after all your callbacks are done. You could put state in a common location for each of your callbacks and use it after the callbacks are done.

Of course, you would need to wait until all the callbacks are done before you can continue.

Hope this helps.


Launch the message in a separate thread:

[receiver performSelectorInBackground:@selector(doSomething)];

use performSelectorInBackground:withObject: if you wish to pass a parameter.


Convert your "for" loop into the equivalent goto statements. Then break the goto basic blocks into methods and method calls without goto's. Then break the method containing the wait into 2 methods and use an asynchronous call and callback in between them. You may have to save some of the local and for loop's implicit state in instance variables.

Goto's are not always bad. They are just implicit in more readable structured and/or OOP messaging constructs. Sometimes the compiler can't do the conversion for you, so you need to know enough about raw program control sequencing to do it yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜