Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading in Objective-C?

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?

like image 944
suse Avatar asked Feb 18 '10 04:02

suse


People also ask

Is method overloading possible in Objective-C?

Correct, objective-C does not support method overloading, so you have to use different method names.

What is method overloading example?

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() { ... }

What is the difference in method overriding and method overloading in Swift?

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.

What is the other name of method overloading?

In Java, function overloading is also known as compile-time polymorphism and static polymorphism.


2 Answers

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

like image 102
David Gelhar Avatar answered Oct 01 '22 20:10

David Gelhar


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)); 
like image 32
Rad'Val Avatar answered Oct 01 '22 20:10

Rad'Val