Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between casting to id than real class type , objective C

Tags:

objective-c

What could be the difference between below 2 statements?

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

and

UILabel *mainLabel = (UILabel*) [cell viewWithTag:10];
like image 783
Vjy Avatar asked Mar 23 '23 08:03

Vjy


1 Answers

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.

like image 179
Gabriele Petronella Avatar answered Apr 09 '23 06:04

Gabriele Petronella