我是靠谱客的博主 火星上老虎,最近开发中收集的这篇文章主要介绍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指定
错误源码:
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
最后
以上就是火星上老虎为你收集整理的iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit的全部内容,希望文章能够帮你解决iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复