Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic methods in Objective C

In Java you can put in multiple constructors to a class that are called depending on the types and/or number of parameters that are used when an instance is constructed. I assume that there is the equivalent in Objective C.

Can I have a polymorphic method?

I would like to build a method that acts slightly differently according to whether a string is passed or a double?

Does that sound bonkers or is it easy?

like image 490
nerak99 Avatar asked Nov 23 '25 10:11

nerak99


1 Answers

You're thinking of overloaded methods. Due to the way dynamic dispatch is implemented in Objective-C, it isn't currently possible to pass two unrelated types as arguments to the same (or same-named) method and have it understand.

In Objective-C, there are two related but distinct approaches to handling multiple kinds of input. Let's use your example of a string or a double as possible inputs. In Java, you might have:

 void applyWidget(String s);
 void applyWidget(double d);

And that's great, but not Objective-C. In Objective-C, you instead would use two different method names:

- (void)applyWidgetWithName: (NSString *)name;
- (void)applyWidgetWithValue: (double)value;

The same logic is in each method as in the Java version, but the distinct names let the compiler treat them as distinct methods (which they are, even in Java.) The code also becomes self-documenting: by reading it, you get an idea of what's happening even without comments. Alternatively, if you simply must have one method name, you change the parameter type to id and accept any object:

- (void)applyWidget: (id)widget;

Then pass either an NSString or an NSNumber wrapping your double. Then, in the implementation of the method, use Objective-C's introspection methods to determine how to proceed:

if ([widget isKindOfClass: [NSString class]]) {
    ...
} else if ([widget isKindOfClass: [NSNumber class]]) {
    double d = [widget doubleValue];
    ...
}

This approach essentially tells callers "send anything--I'll handle it appropriately." It can be difficult to determine the behaviour of such a method without extensive documentation.

like image 195
Jonathan Grynspan Avatar answered Nov 28 '25 01:11

Jonathan Grynspan