2012-02-12 50 views
3

我有一个名为功能的类文件,我保持重复的任务。其中的一个函数称为GetPrice,它连接到XML Web服务,解析XML并返回一个CarPrice对象。一切都很好,直到返回CarPrice对象。即使在我的connectionDidFinishLoading中,它也是NULL,该对象不是null。IOS 5.0 - NSURLConnection的工作原理,但返回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;被填充的熔点之前发生了什么?我需要在这里使用同步连接来确保数据在返回之前填充吗?

回答

2

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

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

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

  • 开始连接
  • 接收数据...
  • 呼叫[mainClass didReceiveAllData:mp]

希望这有助于。

+0

by mainClass,你的意思是调用GetPrice函数的MainViewController吗? 林真的不知道该怎么办.... 我的问题是,我做像这样多次调用该函数: CarPrice * HP = [FN用getPrice:@“本田”]; CarPrice * tp = [fn GetPrice:@“toyota”]; CarrPrice * cp = [fn GetPrice:@“chevrolet”]; 我需要的那些对象之前,我真的可以继续使用应用程序...我不知道如何将这些对象分配给'didReceiveAllData:mp]'函数,并能够保持它们作为不同的对象。 – user1205315 2012-02-12 17:50:15

+0

另外,是否有任何人都知道这样的事情的实际工作演示?教程什么的。我是一名C#开发人员,所以在这种情况下伪代码并不适合我,因为我没有示例将它与 – user1205315 2012-02-12 18:18:11

+0

进行比较关于您的第一条评论:是的。您应该定义一个函数(例如'didReceiveAllData',但您可以调用它,然后调用它),然后处理所有传入的信息。该方法应该在您要调用的类中[fn GetPrice],例如您所说的MainViewController。我不认为这是一个很好的代码示例。但是,如果你对Objective C和委托人不擅长,你可能只想坚持一个Synchronous连接,在你的情况下这很容易使用。 – Robbietjuh 2012-02-12 18:51:20

相关问题