我是靠谱客的博主 火星上老虎,这篇文章主要介绍iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit,现在分享给大家,希望可以做个参考。

错误全文:

Implicit use of ‘self’ in closure; use ‘self.’ to make capture semantics explicit

swift版本:3.0

Xcode版本:8.0

错误原因:

在closure(闭包)内调用当前对象的属性或方法的时候,没有明确添加self指定

错误源码:

复制代码
1
2
3
4
5
let editAction = UITableViewRowAction(style: .default, title: "编辑", handler: { (action,indexPath) -> Void in performSegue(withIdentifier: "ToEditSegue", sender: self.tableView.cellForRow(at: indexPath)) })

修正源码:

复制代码
1
2
3
4
5
6
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

最后

以上就是火星上老虎最近收集整理的关于iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit的全部内容,更多相关iOS开发bug消灭之:Implicit内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部