zoukankan      html  css  js  c++  java
  • iOS NSProxy的一点应用

    1、解引用

    场景:使用CADisplayLink的定时器时,target是自己的情况下被强引用,即使使用weakself也无效的情况

    原理:使用Proxy类型占用target(self),使用方法实现消息转发,也就是说定时器不在占有target,而使用proxy类

    实现代码:

    定时器:

    _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(tick:)];
    [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];

    proxy:

    #import <Foundation/Foundation.h>
    
    @interface YYWeakProxy : NSProxy
    
    @property (nonatomic, weak, readonly) id target;
    
    - (instancetype)initWithTarget:(id)target;
    
    
    + (instancetype)proxyWithTarget:(id)target;
    
    @end
    @implementation YYWeakProxy
    
    - (instancetype)initWithTarget:(id)target {
        _target = target;
        return self;
    }
    
    //类方法
    + (instancetype)proxyWithTarget:(id)target {
        return [[YYWeakProxy alloc] initWithTarget:target];
    }
    
    #pragma mark - over write
    
    //重写NSProxy如下两个方法,在处理消息转发时,将消息转发给真正的Target处理
    - (void)forwardInvocation:(NSInvocation *)invocation {
        [invocation invokeWithTarget:self.target];
    }
    //
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
        return [_target methodSignatureForSelector:selector];
    }

  • 相关阅读:
    习惯
    mysql
    mysql
    mysql
    MYSQL
    MYSQL
    mysql
    手动从Spring中获取指定对象
    jdbc连接数据库
    java代码调用exe(cmd命令)
  • 原文地址:https://www.cnblogs.com/chaochaobuhuifei55/p/9100006.html
Copyright © 2011-2022 走看看