Created
September 7, 2015 02:30
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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