2010-03-27 117 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