2011-07-07 42 views
10

運行此:爲什麼valueForKey:在UITextField上引發UITextInputTraits屬性的異常?

@try 
{ 
    NSLog(@"1. autocapitalizationType = %d", [self.textField autocapitalizationType]); 
    NSLog(@"2. autocapitalizationType = %@", [self.textField valueForKey:@"autocapitalizationType"]); 
} 
@catch (NSException *exception) 
{ 
    NSLog(@"3. %@", exception); 
} 

輸出這樣的:

1. autocapitalizationType = 0 
3. [<UITextField 0x6c15df0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key autocapitalizationType. 

我期待:

1. autocapitalizationType = 0 
2. autocapitalizationType = 0 

此例外只屬於UITextInputTraits協議的一部分性質發生。 常規UITextField這樣的屬性可以通過valueForKey:訪問clearButtonMode

那麼,爲什麼你不能訪問UITextInputTraits屬性與鍵值編碼?

+0

可能由於實施細節。您應該向Apple提交[bug報告](http://bugreport.apple.com)。 –

回答

4

如果你深入到UIKit框架,開闢UITextField.h,你會發現:

@interface UITextField : UIControl <UITextInput, NSCoding> { 
    @private 

    UITextInputTraits *_traits; 
    UITextInputTraits *_nonAtomTraits; 

您還會發現clearButtonMode被聲明爲的UITextField頭文件@property,但autocapitalizationType(和協議的其餘部分)都不是。

您和我看不到UITextField.m,所以我們可以真正得出結論是蘋果以不符合KVC的方式實施UITextFieldUITextInputTraits協議。據推測,將代碼膠合到某處可以將[myTextField autocapitalizationType]轉換爲適當的值,但無論幕後的魔法發生在哪裏,都將停止使用valueForKey:

2

這是我的解決方法:我爲每個實施textInputTraits方法的課程調試了valueForKey:。如果密鑰是UITextInputTraits密鑰,則請在對象的textInputTraits上調用valueForKey:而不是對象本身。

以下是實施細節:1,23

相關問題