这个问题纯属好奇。
在 Xcode 中,为什么会这样:
if (view.class == [UITextView class]) {
UITextView *tview = (UITextView *)view;
tview.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
但以下结果会导致错误消息 Property 'textColor' not found on object of type 'UIView *'
:
if (view.class == [UITextView class]) {
(UITextView *)view.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
直觉上,这些应该完成完全相同的事情。
但是如果我将内联转换括在括号中,它就可以正常工作:
if (view.class == [UITextView class]) {
((UITextView *)view).textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
我怀疑这与 C 处理操作顺序的方式有关,但我很想听听解释。谢谢!
最佳答案
if (view.class == [UITextView class]) {
(UITextView *)view.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
由于优先顺序,(UITextView*)
将充当 view.textColor
结果的转换,即 .textColor
将首先在 UIView*
中访问,然后再转换为 UITextView*
if (view.class == [UITextView class]) {
((UITextView *)view).textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
在此,额外的括号将通知编译器需要先计算子表达式,然后再计算其余表达式。因此,这会将 view
转换为 UITextView*
。该表达式的副作用是一个 UITextView*
实例,这意味着 .textColor
属性可以在它所针对的实例上找到。
关于objective-c - objective-c 中使用点符号的内联类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13094412/