2012-10-27 81 views
0

我有一個也是NSURLConnectionDelegate的UIViewController。因此,它定義的行爲,例如:iOS - 單個委託給多個對象。如何改變行爲?

– connection:didReceiveResponse: 
– connection:didReceiveData: 
– connectionDidFinishLoading: 

然而,在此視圖中我有其指定爲代表多個NSURLConnections。我需要在connectionDidFinishLoading中實現自定義行爲:取決於哪個對象調用委託(例如,播放音頻vs顯示圖像vs打開鏈接)

實現此目的的正確方法是什麼?

回答

1

每委託方法通過在NSURLConnection的作爲參數。存儲參考屬性的連接,然後檢查是否傳遞到connectionDidFinishLoading連接參數爲您的音頻連接或圖像連接等

1

你可以聲明每個連接的

@interface YourViewController 
@property (retain, nonatomic) NSURLConnection *audioConnection; 
@property (retain, nonatomic) NSURLConnection *anotherConnection; 

然後,您connectionDidFinishLoading:方法調用這樣每個連接:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
    if (connection == audioConnection) { 
      //doSomething 
    } else if (connection == anotherConnection) { 
      //doSomethingElse 
    } 
} 
0

如果你有很多,不同的類別下下降的URLConnections(比如說10個連接,滿分5是用於音頻,3顯示圖像,2 FO r開放鏈接等),更好的選擇是子類NSURLConnection並創建一個自定義NSURLConnection類。您可以將自己的屬性添加到此類中。並將您自己的自定義標籤定義爲不同類型的連接。在您的UIViewController和委託方法嘗試使用這個子類對象,並使用此tag屬性不同NSURLConnections之間進行區分。

對於如: -

創建CustomNSURLConnection文件,並寫入,

#define kAudioConnectionTag 100 
#define kDisplayConnectionTag 200 
#define kOpenURLConnectionTag 300 

@interface CustomNSURLConnection : NSURLConnection 

@property (nonatomic) NSInteger tag; 

UIViewController類,

CustomNSURLConnection *audioConnection = [CustomNSURLConnection ...]; 
audioConnection.tag = kAudioConnectionTag; 

CustomNSURLConnection *displayConnection = [CustomNSURLConnection ...]; 
audioConnection.tag = kDisplayConnectionTag; 

CustomNSURLConnection *openURLConnection = [CustomNSURLConnection ...]; 
audioConnection.tag = kOpenURLConnectionTag; 

- (void)connectionDidFinishLoading:(CustomNSURLConnection *)connection{ 
    if (connection.tag == kAudioConnectionTag) { 
      //code 
    } else if (connection.tag == kDisplayConnectionTag) { 
      //code 
    } else { 
      //code 
    } 
} 
相關問題