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;
被填充的熔點之前發生了什麼?我需要在這裏使用同步連接來確保數據在返回之前填充嗎?
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
另外,是否有任何人都知道這樣的事情的實際工作演示?教程什麼的。我是一名C#開發人員,所以在這種情況下僞代碼並不適合我,因爲我沒有示例將它與 – user1205315 2012-02-12 18:18:11
進行比較關於您的第一條評論:是的。您應該定義一個函數(例如'didReceiveAllData',但您可以調用它,然後調用它),然後處理所有傳入的信息。該方法應該在您要調用的類中[fn GetPrice],例如您所說的MainViewController。我不認爲這是一個很好的代碼示例。但是,如果你對Objective C和委託人不擅長,你可能只想堅持一個Synchronous連接,在你的情況下這很容易使用。 – Robbietjuh 2012-02-12 18:51:20