等待代码完成执行 [英] Wait for code to finish execution

查看:131
本文介绍了等待代码完成执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在目标c项目中等待代码完成执行的最简单方法,因为我正在调用Web服务并检索结果,而是在Web服务完成调用和填充之前检索结果.

I would like to know the easiest way to wait for code to finish execution within an objective c project because I am calling a webservice and retrieving the results and instead it is retrieving the results before the webservice has finished being called and filled.

有什么建议吗?

这是我的网络服务代码:

Btw this is my webservice code:

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl];

[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[theRequest addValue:@"http://tempuri.org/GetCategory" forHTTPHeaderField:@"SOAPAction"];

NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]];

[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];

[theRequest setHTTPMethod:@"POST"];

[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

以及我用来从另一个类调用此方法的代码:

and the code I am using to call this method from the other class:

images = [ws callWebService:api :data];

        images = [ws returnArray];

现在的问题是,第二行在第一行完成之前就已经执行了

now the problem is, that the second line is being executed before the first has finished

推荐答案

您可以轻松地按以下步骤进行操作,

You do it easily as below,

-(void)aFunc {

Do Asynchronous A job...

while (A is not finished) {
// If A job is finished, a flag should be set. and the flag can be a exit condition of this while loop

// This executes another run loop.
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

}

Do things using the A's result.

}

这篇关于等待代码完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆