【问题标题】:How to call web service inside of forloop?如何在 for 循环中调用 Web 服务?
【发布时间】:2015-06-02 13:35:08
【问题描述】:

如何在 for 循环中调用 Web 服务?我有两个网络服务。首先,我调用一个 Web 服务并返回一些数据(名称、用户 ID 等)。我使用这个用户标识来调用下一个服务。我想在一个滚动中显示骆驼的所有数据(例如,两只骆驼每人都有很多照片和视频),并且我想在新的滚动视图中列出所有图像和视频。

我的代码如下所示:

-(void)listiingNewCamels
{
    int numberOfCamels = [msgArray count];
    for (int i = 0; i < numberOfCamels; i++)
    {
        camObject=(IZCamelObject *)[msgArray objectAtIndex:i];
        CGFloat yOrigin = i * 395;
        UIView*mySampleview = [[UIView alloc] initWithFrame:CGRectMake(34,yOrigin+20,702,365)];
        mySamplev.backgroundColor=[UIColor redColor];
        camelIDStr=camObject.CamelID;

        UIScrollView *myCamelImagesScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(34,30,640,180)];
        myCamelImagesScroll.backgroundColor=[UIColor greenColor];
        [mySampleview addSubview:myCamelImagesScroll];
        [_camelListingScrol mySampleview];
    }
    _camelListingScrol.contentSize = CGSizeMake(395, numberOfCamels * 400);
}

【问题讨论】:

    标签: ios objective-c web-services


    【解决方案1】:

    网络服务调用可能需要几秒钟才能完成每个调用,如果连接速度慢或服务器没有立即响应,则可能需要更长时间。

    你不能将 GUI 代码和慢的同步代码结合在一起,例如假设你的 for 循环在伪代码中是这样的:

    for (int i = 0; i < numberOfCamels; i++)
    {
        get camel info from camObject
        make synchronous web service call 1
        make synchronous web service call 2
        create scroll view
     }
    

    假设每个 Web 服务调用需要 2 秒,而您有 10 只骆驼,这意味着 for 循环将需要 20 秒才能完成。您的应用 GUI 将挂起 20 秒,用户将无法使用它。

    因此,您必须使您的 Web 服务调用异步,并且您还必须决定如何相应地设计您的程序。

    如何做到这一点取决于您,您可以做的一件事是立即使用 IZCamelObject 中的骆驼信息绘制滚动视图,并在每个 Web 服务调用完成时更新滚动视图。

    或者当应用启动你的模型时(你知道 MVC 吗?)立即开始进行 Web 服务调用,这样当你的 GUI 滚动视图调用它已经(或大部分)的骆驼数据的模型时已下载。

    您的思维方式以及程序设计需要从同步变为异步。在找到解决方案之前,您需要先决定如何处理异步数据下载。

    GUI 代码不应进行 Web 服务调用,这应该是模型组件的职责,但为了说明以异步方式更新滚动视图的概念,它在伪代码中可能如下所示:

       create scroll view
       for (int i = 0; i < numberOfCamels; i++)
        {
            get camel info from camObject
            add a subview with info from camObject
            make asynchronous web service call 1 with completion block: {update subview with data from web service call 1}
            make asynchronous web service call 2 with completion block: {update subview with data from web service call 2
         }
    

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 2016-07-10
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多