問(wèn)題: 我昨天發(fā)現(xiàn)我的導(dǎo)航控制器在pop的時(shí)候居然沒有走dealloc方法旭咽,我在leaks里面去運(yùn)行幼苛,也沒有發(fā)現(xiàn)內(nèi)存泄漏的提示。
歸根結(jié)底恬涧,是因?yàn)楫?dāng)前控制器被某個(gè)對(duì)象強(qiáng)引用在控制器pop的時(shí)候count沒有減為0注益,導(dǎo)致控制器的引用計(jì)數(shù)不為0,系統(tǒng)無(wú)法幫你釋放這部分內(nèi)存溯捆。
總結(jié)了一下控制器被強(qiáng)引用不走dealloc的原因無(wú)非就是三種常見情況:
一.block塊使用不當(dāng)丑搔。因?yàn)閎lock會(huì)對(duì)方法中的變量自動(dòng)retain一次。請(qǐng)檢查控制器中block代碼,對(duì)視圖控制器的強(qiáng)引用提揍。
二.NSTimer沒有銷毀啤月。在viewWillDisappear之前需要把控制器用到的NSTimer銷毀。
三.控制器中的代理屬性一定要是弱引用劳跃,不要強(qiáng)引用谎仲。
而我遇到的恰好不是這3種情況:而是下面這一種,第4種
UIAlertController的循環(huán)引用問(wèn)題
- 在使用時(shí)有一個(gè)特別容易被忽視的地方就是在 handle事件中使用了 UIAlertController控制器售碳。這里會(huì)造成循環(huán)引用强重,在堆內(nèi)存中殘留大量的無(wú)用對(duì)象無(wú)法被銷毀。
引起的原因
a.創(chuàng)建的UIAlertAction會(huì)被UIAlertController的一個(gè)actions屬性引用贸人。
b.在UIAlertAction中他的handler代碼塊 會(huì)引用UIAlertController對(duì)象(如果是直接使用UIAlertController對(duì)象)间景。
c.actions屬性又被UIAlertController對(duì)象引用。
解決辦法
__weak typeof (alertController) weakAlertController = alertController;
__weak typeof (self) weakSelf = self;
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"就餐人數(shù)" message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"請(qǐng)輸入人數(shù)";
textField.keyboardType = UIKeyboardTypeNumberPad;
textField.delegate = weakSelf;
}];
__weak typeof (alertController) weakAlertController = alertController;
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
UITextField * tf = weakAlertController.textFields.lastObject;
cell.detailTextLabel.text = tf.text;
pepoleCountString = cell.detailTextLabel.text;
[table reloadData];
}];
[alertController addAction:cancelAction];
[alertController addAction:sureAction];
[self presentViewController:alertController animated:YES completion:nil];
}