Objective-c – Dynamic binding seems like a lie

dynamic-bindingobjective c

Objective-C uses dynamic binding: that is method calls are resolved at runtime.

Fine.

And use of dot notation really boils down to a method call

But, why then, can't I do something like this:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


  // Intercept the exception
  @try
  {
    @throw [ NSException 
            exceptionWithName:@"Exception named ME!" 
            reason:@"Because i wanted to" 
            userInfo:nil ] ;
  }
  @catch( id exc ) // pointer to an exception object?
  {



    //NSLog( @"%@ : %@\n", exc.name, exc.reason ) ; // ILLEGAL:  Request for member 
    // 'name' in something not a structure or union..
    // If objective-c uses dynamic binding, and dot notation
    // boils down to calling the getter, then
    // WHY do I have to cast to the concrete type here?

    // Only works if I cast to the concrete type NSException*
    NSException* nexc = (NSException*)exc ;
    NSLog( @"%@ : %@\n", nexc.name, nexc.reason ) ;



  }



  [pool drain];
    return 0;
}

When I hear "dynamic binding" I'm thinking "so it should behave like a scripting language", and I'm surprised how inflexible Objective-C seems compared to a scripting language like JavaScript.

Best Answer

You are confusing the runtime and the compiler. The runtime has no problem coping with that. The issue is that dot notation (which is syntactic sugar) requires type information for the compiler to disambiguate between Objective-C objects and C structs.

If you don't use dot notation it works:

NSLog( @"%@ : %@\n", [exc name], [exc reason]) ;

The above will generate a warning if the type is not id since the compiler knows it does know the type and can't guarantee the dispatch will work, but it will compile and run.

Fundamentally the issue at hand is the compiler needs to know whether to generate a structure load, or an Objective C dispatch, in other words, with dot notation it needs to have enough information to determine the difference between an object and a scalar type.