2009-11-17 56 views
9

self.delegate = self;這樣做有什麼問題? 以及正確的做法是什麼?self.delegate = self;這樣做有什麼問題?

謝謝,尼爾。

代碼:

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

注意:這是一個文本字段,當我委託設置到另一個對象(self.delegate = MAINVIEW)一切工作正常,但我將不得不在mainView中實現委託方法,並且我想把它們放在自己(我創建的一個uiTextField類)中。如果我設置self.delegate = self,我會得到一個textField,但鍵盤不顯示。

+0

請澄清一下:你爲什麼知道我錯了。發生了什麼 – 2009-11-17 10:04:31

+0

嗨。這是一個文本字段, ,當我將代理設置爲另一個對象(self.delegate = mainView)時,一切正常,但是隨後我將不得不在mainView中實現委託方法,並且我想將它們放入自己(我創建的一個uiTextField類)。 如果我設置self.delegate = self,我會得到一個textField,但鍵盤不顯示。 – Tiger 2009-11-19 07:02:56

+0

在OP中添加了對該問題的評論。 – 2015-05-20 00:49:08

回答

12

看到這個線程

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

基本上,「凍結」當你作爲一個代表是respondsToSelector被自稱點擊你的UITextField與自身的原因 - >無限遞歸。

UITextField是唯一AFAIK。你通常可以使用一個類作爲自己的委託,沒有特別的問題。對於UITextField,您必須創建一個實際的委託(當然,這可以調用UITextField上的委託方法),請注意避免保留循環,即使您使用ARC也是如此()。

+1

僅供參考:iOS 8以上允許self.delegate =自我引用。 – 2015-08-04 13:59:29