I’m just trying to get a deeper understanding of Objective C.
Why do I have to cast before the call to avoid a warning? Isn’t this a piece of cake for the compiler? Are there any dynamic aspects that I’m missing?
if ([a.class conformsToProtocol:@protocol(P1)])
{
[(id<P1>)a p1Message];
}
I mean, I understand it in a C/C++ point of view, but after all I’m using an Objective C compiler and I don’t like casts. 🙂
If
ais a specific type that declares itself at compile time as implementingP1then you shouldn’t need to cast.If
ais of typeidthen you’ll need to cast only if the return type is ambiguous and you’re actually using it, or if it had parameters. That’ll generally mean that there are multiple method signatures for the method namep1Messageso the compiler doesn’t know which to expect.If
ais of some type that doesn’t declare itself as implementingP1then — unless it separately (and repetitiously) declaresp1Message— you’ll get a warning because you’re calling a method that the object may not implement.If I had to guess, probably
ais declared as being of typeidrather thanid <P1>(which is more normal for, say, delegates) and you have multiplep1Messages flying around. You might also put the cast in proactively because one day you might have multiple different messages with the same name and someone else that might implementp1Messageshouldn’t have to know every other place in the project that somebody uses that method name.The compiler can’t induce from the
conformsToProtocol:check that it is safe to callp1Messageexactly because it’s a dynamic runtime. You may have substituted a different implementation ofconformsToProtocol:either at compile time or at runtime, meaning that it isn’t safe to assume that the compiler knows what it does. That call will be dynamically dispatched just like any other.