为什么 UITextField 上的 valueForKey: 会引发 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 的常规属性(例如具有 clearButtonMode
)可以通过 valueForKey:
访问。
那么为什么不能使用键值编码访问 UITextInputTraits
属性呢?
Running this:
@try
{
NSLog(@"1. autocapitalizationType = %d", [self.textField autocapitalizationType]);
NSLog(@"2. autocapitalizationType = %@", [self.textField valueForKey:@"autocapitalizationType"]);
}
@catch (NSException *exception)
{
NSLog(@"3. %@", exception);
}
Outputs this:
1. autocapitalizationType = 0
3. [<UITextField 0x6c15df0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key autocapitalizationType.
I was expecting:
1. autocapitalizationType = 0
2. autocapitalizationType = 0
This exception only happens with properties that are part of the UITextInputTraits
protocol. Regular properties of a UITextField
such has clearButtonMode
can be accessed through valueForKey:
.
So why can't you access UITextInputTraits
properties with key-value coding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您深入研究 UIKit 框架并打开
UITextField.h
,您会发现:您还会发现
clearButtonMode
被声明为@property< /code> 在 UITextField 头文件中,但
autocapitalizationType
(以及UITextInputTraits
协议的其余部分)不是。你和我都看不到
UITextField.m
,所以我们真正能得出的结论是 Apple 实现了UITextField
的UITextInputTraits
协议在某种程度上不符合 KVC 标准。据推测,某处的粘合代码会将[myTextField autocapitalizationType]
转换为适当的值,但无论发生什么幕后魔法,都会停止valueForKey:
。If you delve into the UIKit framework and open up
UITextField.h
, you'll find:You'll also find that
clearButtonMode
is declared as a@property
in the UITextField header file, but thatautocapitalizationType
(and the rest of theUITextInputTraits
protocol) are not.You and I don't get to see
UITextField.m
, so all we can really conclude is that Apple implemented theUITextField
'sUITextInputTraits
protocol in a way that's not KVC compliant. Presumably glue code somewhere converts[myTextField autocapitalizationType]
into the appropriate value, but whatever behind-the-scenes magic is taking place stops short ofvalueForKey:
.这是我的解决方法:我为每个实现
textInputTraits
方法的类混合了valueForKey:
。如果键是 UITextInputTraits 键,则在对象的textInputTraits
而不是对象本身上调用valueForKey:
。以下是实现细节:1,2 和 3。
Here is my workaround: I swizzled
valueForKey:
for every class implementing thetextInputTraits
method. If the key is a UITextInputTraits key, then callvalueForKey:
on the object'stextInputTraits
instead of the object itself.Here are the implementation details: 1, 2 and 3.