美文网首页
iOS UITableView中左滑按钮内存泄漏的坑

iOS UITableView中左滑按钮内存泄漏的坑

作者: 某某香肠 | 来源:发表于2018-08-30 00:33 被阅读0次

通常而言,iOS系统中的大部分block都不需要防循环引用。在最近的工作中,遇到了一个需要防循环引用的地方(也就是需要用到weakSelf/strongSelf的组合)那就是UITableViewRowAction。

UITableViewRowAction

该控件是tableView上的左滑按钮,通常在tableViewDelegate中的方法
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?这个方法上进行配置。
而UITableViewRowAction的初始化方法需要传入一个block,以执行点击按钮后的回调。在这个block中不能强引用self,否则会造成循环引用。

实验验证

验证代码如下

class SecondViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var tableView:UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView = UITableView(frame: self.view.bounds)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorColor = UIColor.gray
        self.tableView.tableFooterView = UIView()
        self.view.addSubview(self.tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action = UITableViewRowAction(style: .normal, title: "delete") {(action, indexpath) in
            print(self.tableView.count)
            
        }
        return [action]
    }

    deinit {
        print("SecondViewController is deinit")
    }
}

代码中的SecondViewController由FirstViewController通过导航控制器push进来。在不对TableView进行左滑操作时,SecondViewController可以被正常释放掉,而在左滑操作后点击左滑的按钮时,SecondViewController也可以被正常释放。但是,在进行左滑操作后不点击按钮而直接返回FirstViewController,则SecondViewController不会被释放掉。为了防治内存泄漏,不能让其block强引用self。

相关文章

网友评论

      本文标题:iOS UITableView中左滑按钮内存泄漏的坑

      本文链接:https://www.haomeiwen.com/subject/pnplwftx.html