views:

618

answers:

1

Hi, self.delegate = self; what's wrong in doing that? and what is the correct way of doing it?

Thanks, Nir.

Code:

(UITextField*)initWith:(id)sender:(float)X:(float)Y:(float)width:(float)hieght:(int)textFieldTag { 
    if (self = [super initWithFrame:CGRectMake(X, Y,width, hieght)]) {
     finalText = [[NSMutableString alloc] initWithString:@""];
     senderObject = sender;
     self.textColor = [UIColor blackColor]; 
     self.font = [UIFont systemFontOfSize:17.0]; 
     self.backgroundColor = [UIColor whiteColor]; 
     self.autocorrectionType = UITextAutocorrectionTypeNo;   
     self.keyboardType = UIKeyboardTypeDefault;     
     self.returnKeyType = UIReturnKeyDone; 
     self.clearButtonMode = UITextFieldViewModeWhileEditing;    
     self.tag = textFieldTag;        
     self.delegate = self;    
     [sender addSubview:self];
    }
    return self;
}
+2  A: 

Why would you do it? A delegate lets you call another object to perform some action without having to include a pointer to everything and turning your code into spaghetti.

What advantage would

[self.delegate someMethod];

have over

[self someMethod];

? I could see a situation where an object acting as a delegate could become available where it was not initially but in that case why not

if(self.delegate == nil)
    [self someMethod];
else
    [self.delegate someMethod];
Adam Eberbach
If you're still interested, I just had to do this very thing. I was writing a scrollable grid class for iPhone, which subclasses UIScrollView. I need to handle the methods called by UIScrollView in my grid view class, so I set the delegate to self.
johnw188