Pages

Saturday, June 12, 2010

Objective-C. Forwarding Messages.

Forwarding messages. It's an absolutely new feature for me in Object-Oriented Programming. I found this thing working in Objective-C (thanks to the book - on the left).
#import <Foundation/Foundation.h>

@interface Cat : NSObject
- (void) meow;
@end

@interface Dog : NSObject
- (void) woof;
@end

@implementation Cat

- (void) meow
{
NSLog( @"%@: Meow", [self className] );
}

@end

@implementation Dog

- (void) woof
{
NSLog( @"%@: woof", [self className] );
}

- (NSMethodSignature*) methodSignatureForSelector:(SEL)selector
{
NSString* name = NSStringFromSelector( selector );
NSLog( @"-[%@: methodSignatureForSelector: %@]", [self className], name );

if ([Cat instancesRespondToSelector: selector])
return [Cat instanceMethodSignatureForSelector: selector];

return [super methodSignatureForSelector: selector];
}

- (void) forwardInvocation:(NSInvocation *)anInvocation
{
NSString* name = NSStringFromSelector( anInvocation.selector );
NSLog( @"-[%@: forwardInvocation: %@]", [self className], name );

id theCat = [[Cat alloc] init];
NSLog( @"Forwarding '%@' to %@", name, theCat );
[anInvocation invokeWithTarget: theCat];
[theCat release];
}

@end

int main()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

id dog = [[Dog alloc] init];
[dog woof];
[dog meow];
[dog release];

[pool drain];
return 0;
}
And here is the output:

Running…
Dog: woof
-[Dog: methodSignatureForSelector: meow]
-[Dog: forwardInvocation: meow]
Forwarding 'meow' to
Cat: Meow

No comments:

Post a Comment