9

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;
} 

Notes: This is a text field, and when I am setting the delegate to another object (self.delegate = mainView) everything works fine, but then I will have to implement the delegate methods in mainView, and I would like to put them in self (a uiTextField class which I have created). If I am setting self.delegate = self, I do get a textField but the keyboard doesn't show up.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Tiger
  • 383
  • 1
  • 5
  • 13
  • please clarify: Why do you know that i is wrong. What's happening – Kai Huppmann Nov 17 '09 at 10:04
  • Hi. This is a text field, and when I am setting the delegate to another object (self.delegate = mainView) everything works fine, but then I will have to implement the delegate methods in mainView, and I would like to put them in self (a uiTextField class wich I have created). If I am setting self.delegate = self, I do get a textField but the keyboard doesn't show up. – Tiger Nov 19 '09 at 07:02
  • Added comment from OP into the question. – Dan Rosenstark May 20 '15 at 00:49
  • UITextView is unique in not being able to do this. the solution is simple, http://stackoverflow.com/a/13338493/294884 – Fattie Sep 27 '15 at 22:41

1 Answers1

12

See this thread

http://www.cocoabuilder.com/archive/cocoa/241465-iphone-why-can-a-uitextfield-be-its-own-delegate.html#241505

Basically, the reason for the "freeze" when you click on your UITextField with itself as a delegate is that respondsToSelector is calling itself -> infinite recursion.

UITextField is unique AFAIK. You can usually use a class as its own delegate with no particular problems. For UITextField you must create an actual delegate (that could, of course, call methods on the UITextField for which it's a delegate. Just be careful to avoid retain loops, even if you're using ARC).

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421