RunTime之消息转发之NSTimer循环引用的解决方案

消息转发通常用于解耦,在此有个实际例子就是打破NSTimer的引用循环,
YYKit框架中有一个YYWeakProxy类,就是用来处理引用循环的,YYWeakProxy类继承于NSProxy,
自己可以模仿YYWeakProxy写一个WeakProxy类继承自NSProxy代码如下

@property (nonatomic, weak, readonly) id weakTarget;

+ (instancetype)proxyWithTarget:(id)target;
- (instancetype)initWithTarget:(id)target;
@implementation WeakProxy

+ (instancetype)proxyWithTarget:(id)target {
    return [[self alloc] initWithTarget:target];
}

- (instancetype)initWithTarget:(id)target {
    _weakTarget = target;
    return self;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    SEL sel = [invocation selector];
    if ([self.weakTarget respondsToSelector:sel]) {
        [invocation invokeWithTarget:self.weakTarget];
    }
}

//返回方法的签名。
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [self.weakTarget methodSignatureForSelector:sel];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    return [self.weakTarget respondsToSelector:aSelector];
}
@end

原理跟类方法相似,打破循环引用的环路。将timer的target设置为WeakProxy实例,利用消息转发机制实现执行VC中的计时方法,解决循环引用。

NSTimer循环引用解决方案

你可能感兴趣的:(RunTime之消息转发之NSTimer循环引用的解决方案)