美文网首页
NSTimer循环引用解决方案

NSTimer循环引用解决方案

作者: i爱吃土豆的猫 | 来源:发表于2021-04-16 23:52 被阅读0次

文章以在TimerViewController中使用计时器为例,在VC中声明一个NSTimer属性。

创建NSTimer对象:

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];

timer作为VC的属性,被VC强引用,创建timer对象时VC作为target被timer强引用,即循环引用。

image.png

解决循环引用的几种方式:

weak指针:

既然是强引用导致循环引用,那么用__weak修饰self就好了,想法是对的,但是做法是无效的。因为无论是weak还是strong修饰,在NSTimer中都会重新生成一个新的强引用指针指向self,导致循环引用的。

类方法:

创建一个继承NSObject的子类TempTarget,并创建开启计时器的方法。

self.timer = [TempTarget scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerStart:) userInfo:nil repeats:YES];

VC强引用timer,因为timer的target是TempTarget实例,所以timer强引用TempTarget实例,而TempTarget实例弱引用VC,解除循环引用。

image.png
WeakProxy:

创建一个继承NSProxy的子类WeakProxy,并实现消息转发的相关方法。

GCD:
Block:

创建NSTimer的分类NSTimer+UnretainCycle。

+ (NSTimer *)lhScheduledTimerWithTimeInterval:(NSTimeInterval)inerval
                                  repeats:(BOOL)repeats
                                    block:(void(^)(NSTimer *timer))block {
    return [NSTimer scheduledTimerWithTimeInterval:inerval target:self selector:@selector(blcokInvoke:) userInfo:[block copy] repeats:repeats];
}

+ (void)blcokInvoke:(NSTimer *)timer {

    void (^block)(NSTimer *timer) = timer.userInfo;
    if (block) {
        block(timer);
    }
}

VC调用:

self.timer = [NSTimer mxScheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer *timer) {
    NSLog(@"执行了");
}];

相关文章

网友评论

      本文标题:NSTimer循环引用解决方案

      本文链接:https://www.haomeiwen.com/subject/phnswhtx.html