Search code examples
iosobjective-coopprotocolsdelegation

Eliminate repetitive code for Delegation in Objective C


One of 35 header files in project (Handed over to me by some other developer; All of them contains same delegates declaration)

@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...
}

All the delegates declared here contains the same functions. Even their definitions, too. Each of these delegates are declared before their respective ViewController header file Like this:

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

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

Implementation of cancelTapped:

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

Implementation of cancelTapped:

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

Implementation of 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];
}

Now, Coming to the Question: I don't want to repeat it in each and every class (as it is now); I want to make it in cleaner way, Is there any possible solution available ?


Solution

  • Implement the delegate methods in a common superclass, and refactor all of the protocols to be one common TapCallbackDelegate protocol