这个问题纯粹是好奇。
在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属性可以在它所针对的实例上找到。

10-04 16:17
查看更多