IOS 5.0 - NSURLConnection 工作但在完成之前返回 Null

标签 ios nsurlconnection nsurlrequest

我有一个名为 functions 的类文件,我在其中保存重复性任务。其中的一个函数称为 GetPrice,它连接到 XML Web 服务,解析 XML 并返回 CarPrice 对象。在返回 CarPrice 对象之前一切正常。它是 NULL,即使在我的 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 ==================

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

最佳答案

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

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

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

  • 开始连接
  • 接收数据...
  • 调用[mainClass didReceiveAllData:mp]

希望这对您有所帮助。

关于IOS 5.0 - NSURLConnection 工作但在完成之前返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250649/

相关文章:

iPhone 使用 NSURLConnection 发送 POST

iphone - A/同步 NSURLConnection : get response without download data?

objective-c - 我可以通过套接字发送 NSURLRequest 吗?

ios - Apple Push Notification Service 发送重复通知

ios - NSURLConnection 的限制是什么?

ios - 与 Silveright 和 iPad 客户端一起使用的推荐绑定(bind)是什么

cocoa - NSURL 来自 NSURLConnection?

ios - 如何使用AFNetworking 2.0将所有网络请求限制为Wi-Fi连接?

ios - 在刷完最后一个 View Controller 后,如何关闭/弹出 UIPageViewController?

iphone - 在表格 View 单元格中调整图像大小