Latest version of Objective-C and XCode (4.4).
I have a code snippet and I cannot understand why I’m able to use some lines, let me explain :
// For understanding purpose : (NSMutableArray*)_programStack
id l_topItemOnStack = [_programStack lastObject];
if([l_topItemOnStack isKindOfClass:[NSNumber class]])
{
return [l_topItemOnStack doubleValue];
}
My question : since my l_topItemOnStack is of type id and I didn’t cast it into a NSNumber, how am i able to use the [l_topItemOnStack doubleValue].
I guessed that I had to cast it to NSNumber first to access the NSNumber methods…
What am I missing here ?
Because Objective-C is a dynamic language, the message names and their declarations are just hints for the compiler – the actual message lookup and sending occurs at runtime. So even if the compiler doesn’t know your object responds to the
doubleValuemessage, it’s still able to make your call intoas usually.
Furthermore, the compiler looks up all the selectors that are declared anywhere in the included headers, and tries to find the best match using the actual context – here doubleValue is a unique name – it’s declared on NSNumber only, so the compiler assumes that your object is indeed an NSNumber.
If you really want to avoid this, either cast the object when you call the method or initially declare it as an NSNumber.