Difference between casting to id than type of real class, target C

What could be the difference between the statements below?

UILabel *mainLabel = (id) [cell viewWithTag:10]; 

and

 UILabel *mainLabel = (UILabel*) [cell viewWithTag:10]; 
+4
source share
1 answer

The short answer is no.

Both clicks will prevent the compiler from warning about incompatible pointer types.

In any case, since types in Objective-C are not checked at runtime, this will not matter much when it starts.

Actually

 UILabel *mainLabel = (id) [cell viewWithTag:10]; UILabel *mainLabel = (UILabel*) [cell viewWithTag:10]; UILabel *mainLabel = [cell viewWithTag:10]; 

equivalent fully at runtime.

The only noticeable difference is that the compiler will warn you in the third case, because the types do not seem compatible. Due to the principle of Liskov substitution , you cannot assign a generic UIView to UILabel . Throwing it, you tell the compiler: "Believe me, I know that everything will be fine."

From this point of view, however, distinguishing it from id does not really make sense: you make the type more general, while you must narrow it down to the corresponding subclass.

To wrap it as a good practice, it is recommended that you return the return type to the exact class that you expect. This will make more sense, and it will be better to read the code as well.

+7
source

Source: https://habr.com/ru/post/1488910/


All Articles