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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,876评论 1 32
  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 10,679评论 1 23
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 9,379评论 0 5
  • android开发中经常遇到需要处理图片的地方,今天说一下圆角矩形图片的处理 1:直接处理图片本身; 2:重写im...
    释寒阅读 9,666评论 0 14
  • 1.想看《绿皮书》。 2.海艳姐姐周一分享时哭了。 3.中午吃饭玩儿狼人杀 。 4.带教新人。
    Betty读书阅读 35评论 0 0

友情链接更多精彩内容