2012-02-12 44 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

相關問題