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]; }