The only way I know to do function/method overloading is by way of the base class. Is there a way to do it with in the same class with no inheritance?
Here is an example of the only way I know to do function overloading by way of inheriting the base class:
@interface class1: NSObject
-(void) print;
@end
@implementation class1
-(void) print
{
NSLog(@"Hello there");
}
@end
@interface class2: class1
-(void) print: (int) x;
@end
@implementation class2
-(void) print: (int) x
{
NSLog(@"Your number is %d", x);
}
@end
int main(void)
{
class2 *c2 = [class2 new];
[c2 print];
[c2 print: 5];
}
result:
Hello there
Your number is 5
In Objective-C, you cannot overload a function to take different kinds of arguments. For example, the following two methods would not work:
The simplest solution would be to change the method name to follow Apple’s method naming convention and rename the methods like so:
Method names are supposed to be descriptive of the the method’s arguments. Overloading goes against this convention, so it would make sense that it’s not allowed.