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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:告警类型:warning: implicit declaration of function 'gets' is invalid in C99 \[-Wimplicit-function-declaration\]。引用\[2\]:函数“gets”的隐式声明在C99中无效。引用\[3\]:如果只声明函数而没有定义函数(函数的具体实现部分),那么就会直接报错:Error: L6218E: Undefined symbol function“XXX” (referred from main.o)!如果没有声明,但是已经定义了函数,只是会出现警告:Warning: #223-D: function “XXX” declared implicitly!。 问题:Warning: implicit declaration of function 'fmc_erase' is invalid in C99 回答: 这个警告是在C99标准中隐式声明函数'fmc_erase'无效导致的。在C99标准中,如果只声明函数而没有定义函数,会直接报错。如果没有声明但已经定义了函数,只会出现警告。所以,为了避免这个警告,你需要在代码中显式地声明函数'fmc_erase'。 #### 引用[.reference_title] - *1* *2* [warning: implicit declaration of function ‘gets‘ is invalid in C99 [-Wimplicit-function-...](https://blog.csdn.net/qq_50635297/article/details/128265518)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [关于Warning:Implicit declaration of function “xxx” is invalid in C99警告!](https://blog.csdn.net/family20102010/article/details/126155338)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值