CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer會(huì)對(duì)target產(chǎn)生強(qiáng)引用,如果target又對(duì)它們產(chǎn)生強(qiáng)引用,那么就會(huì)引發(fā)循環(huán)引用,舉例如下

@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];
    // 保證調(diào)用頻率和屏幕的刷幀頻率一致,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 機(jī)制消息轉(zhuǎn)發(fā),使用代理對(duì)象
@interface KJProxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
// 使用 weak 不會(huì)對(duì) target 造成強(qiáng)引用
@property (weak, nonatomic) id target;
@end

@implementation KJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    KJProxy *proxy = [[KJProxy alloc] init];
    proxy.target = target;
    return proxy;
}
// 將方法調(diào)用轉(zhuǎn)發(fā)給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中的代理對(duì)象替換成NSProxy

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

@implementation KJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    // NSProxy對(duì)象不需要調(diào)用init,因?yàn)樗緛?lái)就沒(méi)有init方法
    KJProxy *proxy = [KJProxy alloc];
    proxy.target = target;
    return proxy;
}
// 返回proxy.target中的方法簽名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}
// 轉(zhuǎn)發(fā)給proxy.target處理
- (void)forwardInvocation:(NSInvocation *)invocation
{
    if(self.target){
      [invocation invokeWithTarget:self.target];
    }
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容