简体   繁体   中英

What memory management is appropriate for a UITableViewRowAction closure?

Is my use of unowned for self and neither weak nor unowned for tableView appropriate in the following context?

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { [unowned self] (action, indexPath) in
        self.habitsManager.remove(at: indexPath.row)
        self.adjustForRowCount()
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.reloadData()
    }

    return [delete]
}

I don't think you need any capture list in this situation.

The time when use capture list is when we would create a strong reference cycle, which means those objects are pointing to each other and ARC would consider them still in use since the count isn't 0 .

In editActionsForRowAt situation, the closure is not pointing to anything else, just a block of code to be executed.

Tapping one of the action buttons executes the handler block stored with the action object.

Read more about editActionsForRowAt here

In conclusion, it's safe to remove [unowned self] and because you're not using action , you could replace it by _ to make it bit cleaner. And you don't have to call tableView.reloadData() here as well.

let delete = UITableViewRowAction(style: .destructive, title: "Delete") {(_, indexPath) in
    self.habitsManager.remove(at: indexPath.row)
    self.adjustForRowCount()
    tableView.deleteRows(at: [indexPath], with: .fade)
}

By the way, Swift document has some great examples of how ARC works and when to use capture list. You may check it out as well. Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM