在带有点符号的objective-c中的内联类型转换

Mur*_*ock 3 xcode objective-c

这个问题纯属好奇心.

在Xcode中,为什么这样做:

if (view.class == [UITextView class]) {
    UITextView *tview = (UITextView *)view;
    tview.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
Run Code Online (Sandbox Code Playgroud)

但以下结果出现错误消息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.];
}
Run Code Online (Sandbox Code Playgroud)

直觉上,这些应该完成同样的事情.

但是如果我将括号中的内联强制转换为括号,它可以正常工作:

if (view.class == [UITextView class]) {
    ((UITextView *)view).textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
Run Code Online (Sandbox Code Playgroud)

我怀疑它只与C处理操作顺序有关,但我很想听听解释.谢谢!

WDU*_*DUK 5

if (view.class == [UITextView class]) {
    (UITextView *)view.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
Run Code Online (Sandbox Code Playgroud)

由于优先顺序,(UITextView*)将作为结果的一个演员view.textColor,意思.textColor是在第UIView*一个被转换为a之前被访问UITextView*

if (view.class == [UITextView class]) {
    ((UITextView *)view).textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
Run Code Online (Sandbox Code Playgroud)

在这里,额外的括号将通知编译器需要在表达式的其余部分之前首先计算子表达式.因此,这是铸造view是一个UITextView*.该表达式的副作用是一个UITextView*实例,这意味着该.textColor属性可以在它被使用的实例上找到.