gnustep-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: late binding when using id type -- newbie objc question


From: Adam Fedor
Subject: Re: late binding when using id type -- newbie objc question
Date: Mon, 23 Jun 2003 15:25:32 -0600


On Monday, June 23, 2003, at 01:56 PM, Martin Voelkel wrote:
this is because of the different return types of [NSArray addObject:]
and [TestClass addObject:] and the error in this case isn't the
question, but:

why does the compiler try to find out which selector in which class
could be meant by sending 'id' a message?  i ever thought that one of
the major advantages of objc is the late binding (at runtime) when
using the dynamic 'id' typing?  OTOH, the risk is deferred to runtime,
when the application may crash, but i tought that's the general
trade-off between early/late-binding.



Late-binding just means the message isn't bound to a particular object until runtime. Unfortunately, Objective-C doesn't have a way of differentiating between messages with the same name but different return and/or argument types. To Objective C, (picking a better example);

-addNumber: (int)number;
-addNumber: (float)number;

are the same message. However, the compiler knows that they are different and knows that there will be a problem when this message is sent to an object. In your case (knowing the internals of how the runtime works), it isn't really a problem, but the compiler treats it the same way anyway.

Anyway, a work-around is to cast the object:

 ret = [(TestClass *)recv addObject: [[NSObject alloc] init]];

(even if recv isn't a TestClass object, but you know that it implements addObject: in the same way). Or if you really don't like doing that, you could define a protocol:

@protocol MyMessages
- (id) addObject: anObject;
@end

and cast it to that:

 ret = [(id <MyMessages>)recv addObject: [[NSObject alloc] init]];

or you could just arrange not to include <Foundation/NSArray.h> in your file, and the compiler won't know about the other definition of addObject:.






reply via email to

[Prev in Thread] Current Thread [Next in Thread]