Thomas Joulin
Thomas Joulin

Reputation: 6650

Override methods in an Objective C Class

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 !

Upvotes: 3

Views: 742

Answers (3)

andyvn22
andyvn22

Reputation: 14824

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;

Upvotes: 4

Nick Moore
Nick Moore

Reputation: 15847

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

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

Upvotes: 5

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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).

Upvotes: 5

Related Questions