What could be the difference between below 2 statements?
UILabel *mainLabel = (id) [cell viewWithTag:10];
and
UILabel *mainLabel = (UILabel*) [cell viewWithTag:10];
Short answer: none.
Both casts will have the effect of preventing a compiler warning about pointer types incompatibility.
Anyway, since types in Objective-C are not checked at runtime, it won't make a bit of a difference when you run it.
As a matter of fact
UILabel *mainLabel = (id) [cell viewWithTag:10];
UILabel *mainLabel = (UILabel*) [cell viewWithTag:10];
UILabel *mainLabel = [cell viewWithTag:10];
are completely equivalent at runtime.
The only noticeable difference is that the compiler will warn you in the third case, since the types do not appear to be compatible. Due to the Liskov substitution principle, in fact, you cannot assign a generic UIView
to a UILabel
. By casting it you tell the compiler: "trust me, I know this will be ok".
From this point of view, however, casting it to id
doesn't really make sense: you're making the type more generic, whereas you should narrow it down to the proper subclass.
To wrap it up, as a good practice, it's advisable that you cast the return type to the exact class you're expecting. It will make more sense and it's going to be better for code readability as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With