I\'ve been looking at the best way to implement the Visitor design pattern in Objective-C. Since the language doesn\'t support method overloading, a \'traditional\' implementati
You can use some introspection/reflection to make this a bit cleaner. You can't overload method names but you can avoid writing a switch statement like this:
- (void)performTasks:(id)object
{
Class class = [object class];
while (class && class != [NSObject class])
{
NSString *methodName = [NSString stringWithFormat:@"perform%@Tasks:", class];
SEL selector = NSSelectorFromString(methodName);
if ([self respondsToSelector:selector])
{
[self performSelector:selector withObject:object];
return;
}
class = [class superclass];
}
[NSException raise:@"Visitor %@ doesn't have a performTasks method for %@", [self class], [object class]];
}
Your actual performTasks methods would then be named as follows:
- (void)performFooTasks:(Foo *)foo
{
//tasks for objects of class Foo
}
- (void)performBarTasks:(Bar *)bar
{
//tasks for objects of class Bar
}
etc...
Note: If you're using ARC, you'll get spurious warnings by creating selectors from strings in this way because it can't tell at compile time what the retain rules should be for the method parameters. You can silence these warnings using a #pragma, as follows:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:selector withObject:object];
#pragma clang diagnostic pop