简介:通过NSProxy 可以实现类的"伪多继承",demo中KLProxy通过拦截方法修改了cat和dog本来的log
1.VC实现
import "ViewController.h"
#import "KLProxy.h"
#import "Dog.h"
#import "Cat.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
Dog * dog = [Dog new];
Cat * cat = [Cat new];
KLProxy * proxy = [KLProxy alloc];
[proxy transform:cat];
[proxy performSelector:@selector(eat:) withObject:nil];
}
@end
2.cat.m 类
#import "Cat.h"
@implementation Cat
-(void)eat:(NSString*)str{
NSLog(@"猫吃~~~猫吃%@",str);
}
@end
3.Dog.m
#import "Dog.h"
@implementation Dog
-(void)wang:(NSString*)str{
NSLog(@"狗叫~~~狗叫%@",str);
}
@end
proxy.h
@interface KLProxy : NSProxy
-(void)transform:(NSObject*)objc;
@end
proxy.m
#import "KLProxy.h"
@interface KLProxy()
@property(nonatomic,strong)NSObject * objc;
@end
@implementation KLProxy
-(void)transform:(NSObject*)objc{
self.objc = objc;
}
-(void)forwardInvocation:(NSInvocation *)invocation{
if(self.objc){
[invocation setTarget:self.objc];
if([self.objc isKindOfClass:[NSClassFromString(@"Cat") class]]){
NSString *str = @"拦截消息";
[invocation setArgument:&str atIndex:2];
}else{
NSString *str = @"我的小狗狗汪汪叫";
[invocation setArgument:&str atIndex:2];
}
//开始调用方法
[invocation invoke];
}
}
-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
NSMethodSignature * signature = nil;
if([self.objc methodSignatureForSelector:sel]){
signature = [self.objc methodSignatureForSelector:sel];
}else{
signature = [super methodSignatureForSelector:sel];
}
return signature;
}
@end
https://www.jianshu.com/p/923f119333d8
proxy解决NSTimer循环引用的应用
https://www.jianshu.com/p/fca3bdfca42f