As far as my knowledge, Objective-C does not support method overloading. What can be the alternative for this in Objective-C? Or should I always use different method name?
Correct, objective-C does not support method overloading, so you have to use different method names.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required. Overriding is all about giving a specific implementation to the inherited method of parent class.
In Java, function overloading is also known as compile-time polymorphism and static polymorphism.
Correct, objective-C does not support method overloading, so you have to use different method names.
Note, though, that the "method name" includes the method signature keywords (the parameter names that come before the ":"s), so the following are two different methods, even though they both begin "writeToFile":
-(void) writeToFile:(NSString *)path fromInt:(int)anInt; -(void) writeToFile:(NSString *)path fromString:(NSString *)aString;
(the names of the two methods are "writeToFile:fromInt:" and "writeToFile:fromString:").
It may be worth mentioning that even if Objective-C doesn't support method overloading, Clang + LLVM does support function overloading for C. Although not quite what you're looking for, it could prove useful in some situations (for example, when implementing a slightly hacked (goes against encapsulation) version of the visitor design pattern)
Here's a simple example on how function overloading works:
__attribute__((overloadable)) float area(Circle * this) { return M_PI*this.radius*this.radius; } __attribute__((overloadable)) float area(Rectangle * this) { return this.w*this.h; } //... //In your Obj-C methods you can call: NSLog(@"%f %f", area(rect), area(circle));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With