2012-10-15 18 views
0

我有一個視圖控制器,它使用委託協議爲了傳回一個字符串數組。我現在有另一個視圖控制器,我想使用相同的協議,但我已經使用它,我在Xcode Duplicate protocol definition of 'SearchDetailsDelegate' is ignored中得到一個警告。從2個視圖中使用委託協議的適當方式是什麼?

我需要這兩個視圖來傳回父視圖控制器的數組來解析。什麼是更合適的方式來實現我在這裏需要做的事情?關鍵的價值觀是否會成爲這裏的方式?

回答

1

在單獨的.h文件(目標c協議的新文件)中定義協議,然後將其包含在所需的視圖控制器中。不建議在兩個不同的視圖控制器中重新定義相同的協議,因爲它已經在您的案例中

+0

真的很難選擇這兩個答案。我選擇了這個,因爲它更恰當地反映了我正在尋找的答案。 – squarefrog

1

您有幾種選擇:

  1. 重命名你的協議是不同的。

  2. 創建一個外部協議,並通過關於每個視圖

  3. 該協議的屬性添加到您的名爲ParentController觀點與一種類型的它的父。

    @property(strong,nonatomic)ParentViewController * ParentController;

(合成是偏離航向)

然後,在你的viewController,當你實例化視圖分配的viewController作爲父

YourView *childView = [[YourView alloc]init]; 
childView.parentController = self; 

現在你可以添加一個方法在你的viewController可以接收字符串數組

-(void)setStringsArray:(NSArray*)arr{ 
    //do what ever you need with the array 
    //don't forget to add this method to your .h file so it will be visible 
} 

最後從視圖發送字符串數組: [self.parentController setStringsArray:yourArray];

BTW ,如果你想知道什麼查看發送陣列,您可以:

-(void)setStringsArray:(NSArray*)arr fromView:(UIView*)senderView{ 
    //do what ever you need with the array 
    //don't forget to add this method to your .h file so it will be visible 
} 

,並使用

[self.parentController setStringsArray:yourArray fromView:self]; 

BTW 2 的另一種選擇將是使用通知。

+0

這裏有一些很棒的選擇。如果我要創建一個外部協議,我只需創建一個新的NSObject文件並將協議移到那裏?然後,我只是'#import「MyProtocolDefinition.h」',然後'@property(nonatomic,retain)id 委託;'在我的子視圖控制器? – squarefrog

+0

請確保您還在符合該協議的類的.h文件中的接口上方寫入@protocol MyProtocolName – AppleDelegate