iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit

本文详细解析了Swift语言中闭包使用self关键字的原因及其重要性,通过具体实例展示了如何正确地在闭包内引用类成员,避免潜在的内存管理问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误全文:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值