【填坑】关于在 block 遇到的坑

最近在做项目的时候遇到 block 中对象循环引用的问题。 发现自己对 block 还不是特别深入, 有时间对 block 进行下总结回顾。

当时代码是这样的:

-(void)addProgressView
{
    AVPlayerItem *playerItem = self.player.currentItem;
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time){
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds([playerItem duration]);
        self.progressSlider.maximumValue = total;
        self.progressSlider.value = current;
    }];
}

出现警告是:

capturing 'self' stringly in this block is likely to lead to a retain cycle

【填坑】关于在 block 遇到的坑_第1张图片

block 循环引用

block 中会对引用的对象进行retain (引用计数 + 1), 该操作对象又将retain 该 block,从而导致相互retain引起循环引用,它们将永远不会被释放。并且造成内存泄漏。

解决方法:

MRC : 在 block 外,把 self 转换一下加上 __block 字段之后就不会被 retain 了;MRC 中不能使用__ weak

ARC : 在 block 外,把 self 转换一下加上 __weak 字段之后就不会被 retain 了; ARC 中 __block使用无效

【填坑】关于在 block 遇到的坑_第2张图片

你可能感兴趣的:(【填坑】关于在 block 遇到的坑)