1.14. Defining Two or More Methods with the Same Name
Problem
You would like to implement two or more methods with the same name in one object. In object-oriented programming, this is called method overloading. However, in Objective-C, method overloading does not exist in the same way as it does in other programming languages such as C++.
Solution
Use the same name for your method, but keep the number and/or the names of your parameters different in every method:
- (void) drawRectangle{
[self drawRectangleInRect:CGRectMake(0.0f, 0.0f, 4.0f, 4.0f)];
}
- (void) drawRectangleInRect:(CGRect)paramInRect{
[self drawRectangleInRect:paramInRect
withColor:[UIColor blueColor]];
}
- (void) drawRectangleInRect:(CGRect)paramInRect
withColor:(UIColor*)paramColor{
[self drawRectangleInRect:paramInRect
withColor:paramColor
andFilled:YES];
}
- (void) drawRectangleInRect:(CGRect)paramInRect
withColor:(UIColor*)paramColor
andFilled:(BOOL)paramFilled{
/* Draw the rectangle here */
}This example shows a typical pattern in overloading. Each
rectangle can be drawn either filled (solid color) or empty (showing
just its boundaries). The first procedure is a “convenience procedure”
that allows the caller to avoid specifying how to fill the rectangle.
In our implementation of the first procedure, we merely call the
second procedure, making the choice for the caller (andFilled:YES) The second procedure gives
the caller control over filling.
Discussion
You can define two methods with the same name so long as they ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access