2012-04-27 56 views
0

什麼是檢查哪些要求是最好的方法,其委託方法內:檢查哪個請求是從NSURLConnection的委託

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 

} 

現在我有一個NSURLConnection的,我發出請求之前,設置爲NSURLConnection的和裏面didReceiveResponse我做的:

if (self.tempConnection == connection) 

但是有一個方法可行,這將不適合比賽的條件下工作。有一個更好的方法嗎?

+0

可能的複製 - http://stackoverflow.com/questions/332276/managing-multiple-asynchronous-nsurlconnection-connections – 0x8badf00d 2012-04-27 21:11:48

+0

第二個解決方案張貼有其實我做什麼,但正如我所說..競爭條件存在,因爲那 – adit 2012-04-27 21:19:54

+1

什麼比賽條件? – 2012-04-27 22:00:37

回答

5

有在OS5一種更好的方式。忘掉所有那些煩人的代表信息。讓連接建立數據給你,並把你完成的代碼的權利,符合你的起始碼:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.site.com"]]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{ 
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
    NSLog(@"got response %d, data = %@, error = %@", [httpResponse statusCode], data, error); 
}]; 
+0

該解決方案僅適用於完成和失敗狀態。對於進度更新,您仍然需要播放查找實例。 – poetmountain 2013-01-04 22:29:43

1

我看了一堆不同的方式來做到這一點,我發現迄今爲止最清潔,最簡單的爲了管理是使用塊模式。這樣,您可以保證在完成時響應正確的請求,避免競爭條件,並且在異步調用期間您沒有任何變量或對象超出範圍的問題。閱讀/維護代碼也更容易。

兩個ASIHTTPRequest和AFNetworking API提供一個塊模式(ASI但不再支持所以最好用AFNetworking去新的東西)。如果您不想使用這些庫中的一個,但想自己做,可以下載AFNetworking的源代碼並查看它們的實現。但是,這看起來像是很多額外的工作,沒有什麼價值。

1

考慮創建一個單獨的類來作爲代表。然後,對於每個NSURLConnection的催生,實例化委託類的新實例來爲NSURLConnection的

下面是一些簡單的代碼來說明這一點:

@interface ConnectionDelegate : NSObject <NSURLConnectionDelegate> 

...然後實現在.m文件的方法

現在,我猜你可能有你在一個UIViewController子類發佈的代碼(或其他類服務於不同目的)?

無論你蹬掉的要求,使用此代碼:

ConnectionDelegate *newDelegate = [[ConnectionDelegate alloc] init]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; 
[NSURLConnection connectionWithRequest:request delegate:newDelegate]; 

//then you can repeat this for every new request you need to make 
//and a different delegate will handle this 
newDelegate = [[ConnectionDelegate alloc] init]; 
request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; 
[NSURLConnection connectionWithRequest:request delegate:newDelegate]; 

// ...continue as many times as you'd like 
newDelegate = [[ConnectionDelegate alloc] init]; 
request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"<url here">]]; 
[NSURLConnection connectionWithRequest:request delegate:newDelegate]; 

你可以考慮存儲在NSDictionary中或其他一些數據結構中的所有委託對象,以跟蹤它們。我會考慮使用NSNotification在connectionDidFinishLoading後,連接完成的通知,並服務於任何對象從響應創建。讓我知道你是否想要代碼來幫助你形象化。希望這可以幫助!

相關問題