我有一个名为 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/