不調(diào)用dealloc方法

問題: 我昨天發(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)無法幫你釋放這部分內(nèi)存。

總結(jié)了一下控制器被強(qiáng)引用不走dealloc的原因無非就是三種常見情況:

一.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)引用問題

  1. 在使用時(shí)有一個(gè)特別容易被忽視的地方就是在 handle事件中使用了 UIAlertController控制器。這里會(huì)造成循環(huán)引用,在堆內(nèi)存中殘留大量的無用對(duì)象無法被銷毀。
    引起的原因
    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];
        
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容