Search code examples
iosobjective-cdelegatesprotocols

Is it bad design to set self.delegate = self


I have a UIViewController subclass (say MyViewController).

MyViewController.h

@protocol TargetChangedDelegate
    -(void) targetChanged; 
@end

@interface MyViewController

@property (weak) id<TargetChangedDelegate> targetChangedDelegate;

-(void) doSomethingOnYourOwn;

@end

MyViewController.m

@implementation MyViewController <TargetChangedDelegate>

-(void) doSomethingOnYourOwn
{
  // DO some stuff here

  // IS THIS BAD ??
  self.targetChangedDelegate = self;
}

-(IBAction) targetSelectionChanged 
{
  [self.targetChangedDelegate targetChanged];
}

-(void) targetChanged
{
   // Do some stuff here
}

@end

Based on certain conditions a class that instantiates an instance of MyViewController may decide to set itself as the delegate or not.

Foo.m

@property(strong) MyViewController *myVC;

-(void) configureViews
{
  self.myVC = [[MyViewController alloc] init];
  [self.view addSubview:self.myVC];

  if (someCondition) 
  {
    self.myVC.targetChangedDelegate = self;
  }
  else
  {
    [self.myVC doSomethingOnYourOwn]
    //MyViewController sets itself as the targetChangedDelegate
  } 

}

With reference to the code snippet above, I have the following question: Is it a violation of MVC/delegation design pattern (or just a bad design) to say:

self.delegate = self;

Solution

  • There's absolutely no problem with setting the delegate to self. In fact it is a good way to provide default delegate functionality if a delegate is not set by somebody else.

    Obviously, the delegate property has to be declared weak otherwise you get a reference cycle.

    To expand a bit, having read the wrong answer and wrong comments above, if you allow an object to be its own delegate, your code is cleaner because you do not have to surround absolutely every single delegate call with

    if ([self delegate] != nil)
    {
        [[self delegate] someMethod];
    }
    else
    {
        [self someMethod];
    }