views:

157

answers:

3

Hi,

Why can't I do this, and how could I perform the same behavior in Objective C ?

@interface Test
{

}

- (void)test:(Foo *)fooBar;
- (void)test:(Bar *)fooBar;

@end

Thanks in advance !

+3  A: 

This is called overloading, not overriding. Objective-C methods don't support overloading on type, only on the method and parameter names (and "overloading" isn't really a good term for what's going on anyway).

Marcelo Cantos
Thanks ! I got confused ^^ So there is no way to perform the same behavior ? I mean, sending messages with the same names, but having a different behavior depending on the parameter type ? Since I read everywhere that Objc is highly dynamic, I think this is possible, but i'm thinking too much like an C++ programmer
Thomas Joulin
@Thomas, Objective-C was a far less ambitious project than C++. Getting this kind of semantic to work would have made the language far more complex. The simple answer, of course, is that it just isn't that way, whatever the reasons. Also take particular note of @invariant's answer.
Marcelo Cantos
+5  A: 

The convention is to have variations on the method name according to the parameters accepted:

- (void)testWithFoo:(Foo *)foo;
- (void)testWithBar:(Bar *)bar;
invariant
A: 

No, you can't do this. It's actually Obj-C's "highly dynamic" nature, as you put it, that makes it a pretty bad idea; imagine:

id objectOfSomeType = [foo methodReturningId]; //It's not clear what class this is
[Test test:objectOfSomeType]; //Which method is called? I dunno! It's confusing.

If you really, really wanted this behavior, I suppose you could implement it like this:

- (void)test:(id)fooBar
{
    if ([fooBar isKindOfClass:[Foo class]])
    {
        //Stuff
    }
    else if ([fooBar isKindOfClass:[Bar class]])
    {
        //You get the point
    }
}

In all cases I can think of, however, it's most appropriate to use invariant's method:

- (void)testWithFoo:(Foo *)foo;
- (void)testWithBar:(Bar *)bar;
andyvn22
Yep, I suppose that like @Marcelo said, what I want to do is simply not possible in ObjC... Doing what you and @invariant says is certainly the good solution but unfortunately exactly what I wanted to avoid :D
Thomas Joulin