The Unadopted Protocol
The Unadopted Protocol
- Subject: The Unadopted Protocol
- From: Matt Neuburg <email@hidden>
- Date: Wed, 02 Jun 2010 08:57:07 -0700
- Thread-topic: The Unadopted Protocol
Here's something I stumbled on by accident. Consider the following:
// MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
}
@end
// MyClass.m
#import "MyClass.h"
@implementation MyClass
- (void) testing {
NSLog(@"testing");
}
@end
// UnadoptedProtocolAppDelegate.h
#import <Cocoa/Cocoa.h>
... // skipping irrelevant stuff
@protocol Unadopted
- (void) testing;
@end
// UnadoptedProtocolAppDelegate.m
#import "UnadoptedProtocolAppDelegate.h"
#import "MyClass.h"
@implementation UnadoptedProtocolAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
MyClass* mc = [[MyClass alloc] init];
[(id)mc testing];
}
@end
This compiles and runs fine, even though MyClass never adopted the protocol
Unadopted. It take it that by casting mc to an id, I cause the compiler to
grasp at the only signature for "testing" that it knows about, namely the
one in the protocol. So it happily uses that signature without complaint,
and at runtime the correct message is sent to the MyClass instance.
So this appears to be a technique for implementing a highly informal
protocol. (The technique is: define a protocol, don't bother adopting it
anywhere, but send messages defined in that protocol to an id.) My question
is, is this technique:
(a) pointless and lazy
(b) sneaky and clever
(c) just a mistake all round
(d) well known; you only just noticed this??
(e) all of the above
(f) none of the above
:) m.
--
matt neuburg, phd = email@hidden, <http://www.tidbits.com/matt/>
A fool + a tool + an autorelease pool = cool!
AppleScript: the Definitive Guide - Second Edition!
http://www.tidbits.com/matt/default.html#applescriptthings
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden