Typecasting and the id Type

One way to silence the compiler when it warns in the way I’ve just described is by typecasting. A typecast, however, is not a viable way of fixing the problem unless it also tells the truth. It is perfectly possible to lie to the compiler by typecasting; this is not nice, and is not likely to yield nice consequences.

For example, suppose we’ve defined a class MyClass that does contain an instance method rockTheCasbah. As a result, it is fine with the compiler if you send the rockTheCasbah message to a MyClass, although it is not fine to send the rockTheCasbah message to an NSString. So you can silence the compiler by claiming that an NSString instance is a MyClass instance:

NSString* s = @"Hello, world!";
[(MyClass*)s rockTheCasbah];

The typecast silences the compiler; there is no warning. Notice that the typecast is not a value conversion; it’s merely a claim about what the type will turn out to be at runtime. You’re saying that when the program runs, s will magically turn out to be a MyClass instance. Because MyClass has a rockTheCasbah instance method, that silences the compiler. Of course, you’ve lied to the compiler, so when the program runs it will crash anyway, in exactly the same way as before! You’re still sending an NSString a message it can’t deal with, so the very same exception about sending an unrecognized selector to an NSCFString instance will result. So don’t do that!

Sometimes, however, typecasting to silence the compiler is exactly what ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.