objective-c - iOS中[unowned self]的问题
天蓬老师
天蓬老师 2017-04-17 17:43:18
[iOS讨论组]
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let person = people[indexPath.item]

    let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert)
    ac.addTextFieldWithConfigurationHandler(nil)

    ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

    ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
        let newName = ac.textFields![0]
        person.name = newName.text!

        self.collectionView.reloadData()
    })

    presentViewController(ac, animated: true, completion: nil)
}

在上面这段代码中为什么需要[unowned self]

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(3)
迷茫

防止当前VC(self) -> UIAlertController -> 闭包 -> 当前VC的循环引用

另外闭包内的ac参数也应该weak或unowned

怪我咯

可以看下苹果官方文档

developer.apple.com/library
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48

PHP中文网

这段代码来说,并不需要unowned,虽然闭包持有self的引用,但是self并没有持有闭包的引用,所以不构成循环引用。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号