【发布时间】:2012-02-12 16:57:32
【问题描述】:
我有一个名为 functions 的类文件,我在其中保留重复性任务。其中的一个函数称为 GetPrice,它连接到 XML Web 服务,解析 XML 并返回 CarPrice 对象。在返回 CarPrice 对象之前,一切正常。即使在我的 connectionDidFinishLoading 中,它也是 NULL,对象不为 null。
这是我的 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 被填充之前发生?我是否需要在此处使用同步连接来确保在返回之前填充数据?
【问题讨论】:
标签: ios nsurlconnection nsurlrequest