O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required