下面是模拟IDLPainterDeveloper继承IDLDeveloper以及IDLPainter的例子,直接上代码吧:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface IDLDeveloper : NSObject
- (void)coding;
@end
NS_ASSUME_NONNULL_END
|
#import "IDLDeveloper.h"
@implementation IDLDeveloper
- (void)coding { NSLog(@"I Can coding!"); }
@end
|
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface IDLPainter : NSObject
- (void)drawing;
@end
NS_ASSUME_NONNULL_END
|
#import "IDLPainter.h"
@implementation IDLPainter
- (void)drawing { NSLog(@"I Can Drawing!"); }
@end
|
NS_ASSUME_NONNULL_BEGIN
@interface IDLPainterDeveloper : NSProxy
+ (instancetype)createPerson;
@end
NS_ASSUME_NONNULL_END
|
#import "IDLPainterDeveloper.h"
#import "IDLPainter.h" #import "IDLDeveloper.h"
@interface IDLPainterDeveloper ()
@property(nonatomic, strong, readwrite) NSMutableDictionary *methodDictionary;
@end
@implementation IDLPainterDeveloper
+ (instancetype)createPerson { return [[IDLPainterDeveloper alloc] init]; }
- (instancetype)init { IDLPainter *painter = [[IDLPainter alloc] init]; IDLDeveloper *developer = [[IDLDeveloper alloc] init]; [self inheriteMethodsFromSuperTarget:painter]; [self inheriteMethodsFromSuperTarget:developer]; return self; }
- (void)inheriteMethodsFromSuperTarget:(id)target{ if(!target) return; unsigned int numberOfMethods = 0; Method *methodList = class_copyMethodList([target class], &numberOfMethods); for (int i = 0; i < numberOfMethods; i++) { SEL sel = method_getName(methodList[i]); const char *methodName = sel_getName(sel); [self.methodDictionary setObject:target forKey:[NSString stringWithUTF8String:methodName]]; } free(methodList); }
- (void)forwardInvocation:(NSInvocation *)invocation{ SEL sel = invocation.selector; NSString *methodName = NSStringFromSelector(sel); id target = self.methodDictionary[methodName]; if (target && [target respondsToSelector:sel]) { [invocation invokeWithTarget:target]; } else { [super forwardInvocation:invocation]; } }
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{ NSString *methodName = NSStringFromSelector(sel); id target = self.methodDictionary[methodName]; if (target && [target respondsToSelector:sel]) { return [target methodSignatureForSelector:sel]; } else { return [super methodSignatureForSelector:sel]; } }
- (NSMutableDictionary *)methodDictionary { if(!_methodDictionary) { _methodDictionary = [[NSMutableDictionary alloc] init]; } return _methodDictionary; }
@end
|