代码之家  ›  专栏  ›  技术社区  ›  zpesk

返回cocoa中的数组,但等待委派完成

  •  0
  • zpesk  · 技术社区  · 17 年前

    我在cocoa中创建了以下方法:

    -(NSArray *)latestData
    {
        NSURL *requestingURL = [NSURL URLWithString:@"someRestfulURL"];
    
        NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:requestingURL];
        [theRequest setHTTPMethod:@"GET"];
    
        NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
    
        if(theConnection)
        {
            webData = [[NSMutableData data]retain];
        }
        else
        {
            NSLog(@"the connection is NULL");
        }
        return someArray;
    }
    

    我调用的RESTful Web服务返回我使用NSXMLParser解析的XML。

    调用时如何返回数组 latestData 如果我必须等待NSURLConnection和NSXMLParser的委托方法完成,然后才能用适当的数据填充数组?

    2 回复  |  直到 17 年前
        1
  •  1
  •   Daniel    17 年前

    1.使请求同步,这样您将在返回时拥有数组。

        2
  •  1
  •   smorgan    17 年前

    [NSXMLParser parse parse]在解析完成之前不会返回,因此它已经具有您想要的行为,并且NSURLConnection已发送SynchronousRequest:returningResponse:error:用于同步请求。

    如果您在主线程上运行此操作,则应该考虑是否可以异步地使用方法,因为在网络请求上阻塞UI会导致用户体验不佳。