解决Timer以及CADisplayLink循环引用的问题

 #方法一、self _>timer  timer弱引用self 这么能决的解方案;

__weak typeof(self) WeakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
[WeakSelf timerTest];
  }];


    
#方法二、1、通过中间对象(中间对象弱引用)来解决
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[HYTimerProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
@interface HYTimerProxy : NSObject


+(instancetype)proxyWithTarget:(id)target;
@property(nonatomic,weak)id target;

@end

@implementation HYTimerProxy
+(instancetype)proxyWithTarget:(id)target{
    HYTimerProxy * proxy = [[HYTimerProxy alloc]init];
    proxy.target = target;
    return proxy;
}
消息转发
- (id)forwardingTargetForSelector:(SEL)aSelector{
    return self.target;
}
#方法二 2、 NSPorxy
//速度更快
@interface HYTimerProxy : NSProxy
+(instancetype)proxyWithTarget:(id)target;
@property(nonatomic,weak)id target;


@implementation HYTimerProxy

+(instancetype)proxyWithTarget:(id)target{
    //NSProxy 不需要init方法、因为他本身没有init方法
    HYTimerProxy * proxy = [HYTimerProxy alloc];
    proxy.target = target;
    return proxy;
}

放回方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    return [self.target methodSignatureForSelector:aSelector];
}

直接调用
- (void)forwardInvocation:(NSInvocation *)anInvocation{
    [anInvocation invokeWithTarget:self.target];

}

你可能感兴趣的:(解决Timer以及CADisplayLink循环引用的问题)