错误全文:
Implicit use of ‘self’ in closure; use ‘self.’ to make capture semantics explicit
swift版本30">swift版本:3.0
Xcode版本:8.0
错误原因:
在closure(闭包)内调用当前对象的属性或方法的时候,没有明确添加self指定
错误源码:
let editAction = UITableViewRowAction(style: .default, title: "编辑", handler: {
(action,indexPath) -> Void in
performSegue(withIdentifier: "ToEditSegue", sender: self.tableView.cellForRow(at: indexPath))
})
修正源码:
let editAction = UITableViewRowAction(style: .default, title: "编辑", handler: {
(action,indexPath) -> Void in
// 增加了self.关键字
self.performSegue(withIdentifier: "ToEditSegue", sender: self.tableView.cellForRow(at: indexPath))
})
关于为什么要在closure内添加self关键字:
由于closure是异步加载的,所以在closure内的代码真正的被调用的时候需要保证对象仍然存在,由于iOS的ARC机制,这里添加的self实际上等于给对象的引用数+1,在closure结束的时候在释放掉。确保了内存的管理,避免了内存泄漏。
参考&延伸阅读
http://katalisha.com/2016/01/22/ARC-Swift-closures-and-weak-self.html