ios - 知识梳理(造成内存泄漏的原因)

  • block的循环引用
[self.service requestData:^(id data)
{
    self.title = data[@"title"];
}];

这种情况就是典型的循环引用导致内存泄漏,self强引用service, service强引用了block,而block回调时又调用了self,导致block强引用了self,造成循环,无法释放。

解决方案

__weak typeof(self) weakSelf = self;
[self.service requestData:^(id data)
{
    __strong typeof(weakSelf) strongSelf = weakSelf;
    if (strongSelf)
        strongSelf.title = data[@"title"];
}];
  • delegate的循环引用
VC:
testView.delegate = self;
[self.view addSubview: testView];

如上若是testView的delegate属性若为强引用例如(strong, retain)就会造成循环引用

解决方案使用 weak修饰。

  • NSTimer造成强引用
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(run) userInfo:nil repeats:YES];
    }
    return self;
}

- (void)run
{
    NSLog(@"time counter ++ ");
}

- (void)dealloc
{
    NSLog(@" --- dealloc ---- ");
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self removeFromSuperview];
}

NSTimer的内存管理法则有点特别,它是基于runloop运作,runloop会对其进行强引用,timer在添加target的时候 又将self强引用,所以dealloc方法永远不会调用。

  • 非对象的内存处理 

例如

但凡通过quarzt2d中带有creat/copy/retain方法创建出来的值都必须手动的释放

有两种方法可以释放前面创建的路径:

(1)CGPathRelease(path);

(2)CFRelease(path);

  • 大范围遍历

大范围遍历的时候尽量创建自己的 autoReleasePool.

猜你喜欢

转载自blog.csdn.net/evol_f/article/details/82981152