iOS|iOS NSProxy使用
简介:通过NSProxy 可以实现类的"伪多继承",demo中KLProxy通过拦截方法修改了cat和dog本来的log
Log.png 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
@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
【iOS|iOS NSProxy使用】https://www.jianshu.com/p/923f119333d8
proxy解决NSTimer循环引用的应用
https://www.jianshu.com/p/fca3bdfca42f
推荐阅读
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- 2020-04-07vue中Axios的封装和API接口的管理
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- iOS中的Block
- Linux下面如何查看tomcat已经使用多少线程
- 使用composer自动加载类文件
- android|android studio中ndk的使用