避免循环引用

来源:互联网 发布:香港 mac pro 关税 编辑:程序博客网 时间:2024/04/28 11:46

比较常见的避免循环引用的方法

- (void)viewDidLoad {

    [super viewDidLoad];

    __weak typeof(self) weakSelf = self;

    self.block = ^ {

[weakSelf requestDataList];  

    }

}

我们再看一段代码

- (void)viewDidLoad {

    [super viewDidLoad];

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

    NSOperationQueue *mainQuene = [NSOperationQueue mainQueue];

    [center addObserverForName:UIKeyboardWillShowNotification

                        object:nil

                         queue:mainQuene

                    usingBlock:^(NSNotification *note) {

                             [self requestDataList];

                    }];

}

当返回到上一级页面的时候 dealloc 方法没有走,为什么

首先:usingBlock中请求加载数据,block retain self对象,这里没有形成循环引用,但依然造成内存泄漏

原因:center类使用单例设计,走完这个viewDidLoad方法也不会释放,而它指向的block保留了self ,导致 self 引用计数总是不为0

解决办法:将block中的self弱引用

0 0