Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uliwitness/d74ea5563e10d7bea177 to your computer and use it in GitHub Desktop.
Save uliwitness/d74ea5563e10d7bea177 to your computer and use it in GitHub Desktop.
It's annoying that Objective-C doesn't let you provide a default implementation for a protocol. Maybe one could just create a proxy with that?
//
// main.m
// ProtocolImplementations
//
// Created by Uli Kusterer on 07/09/15.
// Copyright (c) 2015 Uli Kusterer. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PISBaseClass : NSObject
-(void) doBaseClassStuff;
@end
@implementation PISBaseClass
-(void) doBaseClassStuff
{
NSLog(@"%@", NSStringFromSelector(_cmd) );
}
@end
@protocol PISMixInProtocol <NSObject>
@optional // Sadly needed or PISSubClass will complain about missing impl.
-(void) doMixInStuff;
@end
@interface PISMixInShim : NSObject <PISMixInProtocol>
-(instancetype) initWithBaseClass: (PISBaseClass*)bc;
-(void) doMixInStuff;
@end
@interface PISMixInShim ()
{
PISBaseClass* baseClassObj;
}
@end
@implementation PISMixInShim
-(instancetype) initWithBaseClass: (PISBaseClass*)bc
{
if( !bc )
return nil;
self = [super init];
if( self )
{
baseClassObj = bc;
}
return self;
}
-(void) doMixInStuff
{
NSLog(@"%@", NSStringFromSelector(_cmd) );
}
-(BOOL) respondsToSelector:(SEL)aSelector
{
if( ![super respondsToSelector: aSelector] )
{
return [baseClassObj respondsToSelector: aSelector];
}
return YES;
}
-(NSMethodSignature *) methodSignatureForSelector:(SEL)aSelector
{
NSMethodSignature *sig = [super methodSignatureForSelector:aSelector];
if( !sig )
sig = [baseClassObj methodSignatureForSelector:aSelector];
return sig;
}
-(void) forwardInvocation:(NSInvocation *)anInvocation
{
[anInvocation invokeWithTarget: baseClassObj];
}
@end
@interface PISSubClass : PISBaseClass <PISMixInProtocol>
-(instancetype) init;
-(void) doSubClassStuff;
@end
@implementation PISSubClass
-(instancetype) init
{
self = [super init];
if( self )
{
}
return (id)[[PISMixInShim alloc] initWithBaseClass: self];
}
-(void) doSubClassStuff
{
NSLog(@"%@", NSStringFromSelector(_cmd) );
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
PISSubClass * sco = [[PISSubClass alloc] init];
[sco doBaseClassStuff];
[sco doSubClassStuff];
[sco doMixInStuff];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment