2010-03-27 115 views
1

我有以下代碼協議片段:iPhone:共享協議/代理代碼

@protocol FooDelegate;

@interface Foo:UIViewController {id}委託; } ...

@protocol FooDelegate ... //方法1 ... //方法2 ... @end

而且,下面的代碼,它實現FooDelegate:

@interface BAR1:的UIViewController {...}

@interface BAR2:的UITableViewController {...}

原來FooDelegate的實現在Bar1和Bar2類上都是一樣的。我目前只是將Bar1的FooDelegate實現代碼複製到Bar2。

如何以Bar1和Bar2在單個代碼庫中共享相同的代碼(不是當前有2個副本)的方式來構造/實現,因爲它們是相同的?

在此先感謝您的幫助。

+0

你解決了你的問題嗎?我面臨的是同樣的事情,我對目前爲止收到的任何答案感到不滿意:( – amok 2010-07-18 19:35:39

回答

0

創建一個新對象,MyFooDelegate:

@interface MyFooDelegate : NSObject <FooDelegate> 

然後BAR1和BAR2可以各自創建它的一個實例(或共享一個實例)。在這些類可以消除委託方法,並添加行喜歡:

MyFooDelegate *myDooDelegateInstance = ...; 

foo.delegate = myFooDelegateInstance; 

你也可以在一個NIB文件創建MyFooDelegate的實例和視圖控制器的委託出口連接到它,如果需要的話。

這樣,您的源文件或可執行文件中就不會有任何重複的代碼。

+0

我認爲這並不能真正解決問題,Bar1和Bar2都需要在所有相同的地方添加代碼連接到他們的MyFooDelegate實例,真正的解決方案將是一種mixins,在這種情況下Cocoa並沒有真正的解決方案 – 2010-03-27 19:23:45

+1

如果問題是在兩個源文件中有相同的代碼,它絕對可以解決這個問題 – benzado 2010-03-27 20:52:27

+1

不是,它將一個問題換成另一個問題,因爲現在你只是在兩個源文件中有一個不同的源代碼。 – 2010-03-27 21:09:10

1

選項A:實現的方法,在類別

使用必須UIViewController聲明的任何屬性。

UITableViewControllerUIViewController的子類。

//UIViewController+MyAdditions.h 
@interface UIViewController (MyAdditions) 
- (void)myCommonMethod; 
@end 

//UIViewController+MyAdditions.m 

@implementation UIViewController (MyAddtions) 
- (void)myCommonMethod { 
// insert code here 
} 

新的方法添加到UIViewControllerBar1被繼承和Bar2

選項B:創建一個MyViewControllerHelper

如果你可以實現你的公共代碼作爲一個類的方法,否則您需要暫時或作爲Bar1Bar2

的屬性創建助手類的實例
@interface MyViewControllerHelper : NSObject 
- (void)myCommonMethod; 
@end 

@implementation MyViewControllerHelper 
- (void)myCommonMethod { 
    // common code here 
} 

@interface Bar1 : UIViewController { 
MyViewControllerHelper *helper; 
} 
@property MyViewControllerHelper *helper; 
@end 

@implementation Bar1 
@synthesize helper; 
- (void)someMethod { 
    [helper myCommonMethod]; 
} 
@end 

@interface Bar2 : UITableViewController { 
MyViewControllerHelper *helper; 
} 
@property MyViewControllerHelper; 
@end 

@implementation Bar2 
@synthesize helper; 
- (void)someOtherMethod { 
    [helper myCommonMethod]; 
} 
@end 
+0

選項A有一些不必要的風險,因爲您會將委託方法添加到系統UIViewController類中。如果委託協議完全是自定義協議,那麼它可能是安全的,但如果它是系統提供的協議(例如UIActionSheetDelegate),理論上可以打破不相關的東西(例如,系統照片選取器視圖控制器)。 – benzado 2010-03-29 18:47:55

+0

它總是關於選擇。選項A完全避免了我認爲可能會導致問題的委託,因爲UIViewController沒有實現委託協議,但UITableViewController可以。 Foo和Bar示例沒有提供足夠的上下文來確定它們是否是API中缺少*的有用實用程序方法(請考慮字符串的base64編碼)。任何風險都必須權衡違反* dry *原則以及管理控制器和新助手對象之間的類別或耦合的複雜性。 – falconcreek 2010-03-30 03:56:59