消除目标C中的委托重复代码

时间:2013-02-14 11:18:04

标签: ios objective-c oop protocols delegation

项目中的35个头文件之一(由其他开发人员交给我;所有这些文件都包含相同的委托声明)

@interface ActivityDetailsCN : UIViewController <NSXMLParserDelegate,     
AccountStatusDelegate, AccountTypeDelegate, DirectionDelegate, RecipientDelegate,
PriorityDelegate, DurationDelegate, CurrencyDelegate, OppTypeDelegate,
OppCategoryDelegate, DatePickerDelegate, SalutationDelegate, DepartmentDelegate, 
LeadTypeDelegate, OwnershipDelegate, MailingDelegate, SourceDelegate, 
StateDelegate, CommentsDelegate, CityDelegate, ZipCodeDelegate> 
{
    //Declaration of iVars goes here...
}

此处声明的所有委托包含相同的功能。甚至他们的定义也是如此。 这些代理中的每一个都在各自的ViewController头文件之前声明,如下所示:

@protocol AccountStatusDelegate <NSObject>
  - (void)cancelTapped;
  - (void)doneTapped;
  - (void)selectTapped:(NSString *)string;
@end

@interface AccountStatusVC : UIViewController <NSXMLParserDelegate> {
}
@property (unsafe_unretained) id <AccountStatusDelegate> delegate;

cancelTapped的实现:

- (void)cancelTapped {
    [objPopOver dismissPopoverAnimated:YES];
}

cancelTapped的实现:

- (void)doneTapped {
    [tblView reloadData];
    [objPopOver dismissPopoverAnimated:YES];
}

cancelTapped的实现:

- (void)selectTapped:(NSString *)string
{
    if ([string isEqualToString:@"US"])
        isTextField = FALSE;
    else if([string isEqualToString:@"Other"]) {
        appDelegate.strCountry = @"";
        isTextField = TRUE;
    }
    [tblView reloadData];
    [objPopOver dismissPopoverAnimated:YES];
}

现在,来到这个问题:我不想在每一堂课中重复它(就像现在一样);我想以更清洁的方式制作它,有没有可用的解决方案?

1 个答案:

答案 0 :(得分:3)

在公共超类中实现委托方法,并将所有协议重构为一个常见的TapCallbackDelegate协议