This question is pure curiosity.
In Xcode, why does this work:
if (view.class == [UITextView class]) {
UITextView *tview = (UITextView *)view;
tview.textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
But the following results in the error message 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.];
}
Intuitively, these should accomplish the exact same thing.
But then if I enclose the inline cast in parentheses, it works fine:
if (view.class == [UITextView class]) {
((UITextView *)view).textColor = [UIColor colorWithRed:0.020 green:0.549 blue:0.961 alpha:1.];
}
I suspect it just has to do with how C handles order of operations, but I would be curious to hear an explanation. Thanks!
Due to order of precedence, the
(UITextView*)will act as a cast on the result ofview.textColor, meaning.textColorwill be accessed within theUIView*first before it’s cast to aUITextView*In this, the extra parentheses will inform the compiler that sub-expression needs to be computed first, before the rest of the expression. As such, this is casting
viewto be aUITextView*. The side effect of that expression is aUITextView*instance, meaning that the.textColorproperty can be found on the instance it’s being used against.