CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer会对target产生强引用,如果target又对它们产生强引用,那么就会引发循环引用,举例如下

@interface ViewController ()
@property (strong, nonatomic) CADisplayLink *link;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
    // 保证调用频率和屏幕的刷帧频率一致,60FPS
    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

}
- (void)timerTest
{
    NSLog(@"%s", __func__);
}
- (void)linkTest
{
    NSLog(@"%s", __func__);
}
  • 解决方法1:使用 block , __weak self
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    [weakSelf timerTest];
}];
  • 解决方法2:利用 Runtime 机制消息转发,使用代理对象
@interface KJProxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
// 使用 weak 不会对 target 造成强引用
@property (weak, nonatomic) id target;
@end

@implementation KJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    KJProxy *proxy = [[KJProxy alloc] init];
    proxy.target = target;
    return proxy;
}
// 将方法调用转发给proxy.target
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}
@end
self.link = [CADisplayLink displayLinkWithTarget:[KJProxy proxyWithTarget:self] selector:@selector(linkTest)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[KJProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

可以将方法2中的代理对象替换成NSProxy

@interface KJProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

@implementation KJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    // NSProxy对象不需要调用init,因为它本来就没有init方法
    KJProxy *proxy = [KJProxy alloc];
    proxy.target = target;
    return proxy;
}
// 返回proxy.target中的方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}
// 转发给proxy.target处理
- (void)forwardInvocation:(NSInvocation *)invocation
{
    if(self.target){
      [invocation invokeWithTarget:self.target];
    }
}
@end

你可能感兴趣的:(CADisplayLink、NSTimer使用注意)