本文不是技術(shù)向的文章,僅記錄小弟我在開發(fā)中遇到的各種坑...
背景
小弟我在自己寫的工具類中經(jīng)常用block傳數(shù)據(jù),而工具類沒有持有block。
直接在block中用self去調(diào)方法,一直沒出現(xiàn)循環(huán)引用的問題,直到我用了MJRefresh...
當(dāng)時(shí)的代碼是這樣的
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
[self doSomething];
}];
在離開VC的時(shí)候發(fā)現(xiàn)dealloc沒有被調(diào)用,就開始排查問題出在哪里。
傻傻地排查了半個(gè)多小時(shí)才想起來(lái)block會(huì)有循環(huán)引用問題...
將代碼改成了這樣就好了
__weak typeof(self) weakSelf = self;
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
[weakSelf doSomething];
}];
使用UIAlertController也要注意循環(huán)引用的問題
下面這段代碼會(huì)導(dǎo)致UIAlertController無(wú)法釋放
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"請(qǐng)輸入充值金額" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *money = alert.textFields[0].text;
...
}];
UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:yesAction];
[alert addAction:noAction];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.keyboardType = UIKeyboardTypeNumberPad;
}];
[self presentViewController:alert animated:YES completion:nil];
當(dāng)UIAlertController加上TextField的時(shí)候,要注意獲取TextField的內(nèi)容時(shí)需要用weakAlert去獲取。
解決方法
在alert創(chuàng)建后聲明weakAlert
__weak typeof(alert) weakAlert = alert;
將yesAction的block中的這段代碼
NSString *money = alert.textFields[0].text;
改成
NSString *money = weakAlert.textFields[0].text;
就可以解決循環(huán)引用的問題