IOS 5.0 - NSURLConnection有效但在完成之前返回Null

时间:2012-02-12 16:57:32

标签: ios nsurlconnection nsurlrequest

我有一个名为functions的类文件,我保留重复的任务。其中一个函数叫做GetPrice,它连接到XML Web服务,解析XML并返回一个CarPrice对象。一切都很好,直到返回CarPrice对象为止。即使在我的connectionDidFinishLoading中,该对象也不为空。

这是我的GetPrice函数:

-(CarPrice*)GetPrice:(NSString *)m
{
    NSString *url =[@"http://myUrl.com"];

    dataWebService = [NSMutableData data];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
    return mp;  //mp is declared as a CarPrice in the @interface section of my funcs class

    //when it gets returned here it is NULL even though....(see below)
}


//Connection Functions=======================


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    [dataWebService setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [dataWebService appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
    ParserMetal *pmr = [ParserMetal alloc];
    mp = [pmr parseMetal:responseString];
    //at this point, the mp is fully populated
    //an NSLOG(@"%@", mp.displayPrice); here will show that the mp object is populated
    //however as stated above, when it returns, it is null.
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Error during Connection: %@", [error description]);
}

//End Connection Functions ==================

在mp填充之前return mp;是否发生了?我是否需要在此处使用同步连接以确保在返回之前填充数据?

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的代码,您将打电话给GetPrice:m:,然后从那里开始连接。使用[connection start]开始连接后,立即返回mp

这意味着连接已启动,但在收到所有数据之前,您已经返回mp。您应该等待接收数据,然后返回mp

您可以为此使用同步方法,或者您可以在主类中实现一个方法,该方法将在{其他类文件'中定义的connectionDidFinishLoading:connection:方法中调用。像这样:

  • 开始连接
  • 接收数据......
  • 致电[mainClass didReceiveAllData:mp]

希望这有帮助。