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 !
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 !
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).
The convention is to have variations on the method name according to the parameters accepted:
- (void)testWithFoo:(Foo *)foo;
- (void)testWithBar:(Bar *)bar;
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;