微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 闭包中循环引用解决方式

Swift 闭包中循环引用解决方

示例说明:开启一个定时器,然后每隔一秒钟加1秒,直到60秒

变量声明

//声明一个定时器变量
var timer: Timer?
var currentSeconds: Int = 0

weak 方式

func testTimer(){

        weak var weakSelf :  CurrentController? = self
        timer = Timer.scheduledTimer(withTimeInterval: 1.0,repeats: true,block: { _ in

            weakSelf?.currentSeconds += 1

            if weakSelf?.currentSeconds == 60{

                weakSelf?.timer?.invalidate()
                weakSelf?.timer = nil
            }
        })
    }

[weak self] 方式

func testTimer(){
        timer = Timer.scheduledTimer(withTimeInterval: 1.0,repeats: true,block: {[weak self] (_) in

            self?.currentSeconds += 1

            if self?.currentSeconds == 60{

                self?.timer?.invalidate()
                self?.timer = nil
            }
        })
    }

[uNowned self] 方式

func testTimer(){

        timer = Timer.scheduledTimer(withTimeInterval: 1.0,block: {[uNowned self] (_) in

            self.currentSeconds += 1

            if self.currentSeconds == 60{
                self.timer?.invalidate()
                self.timer = nil
            }
        })
    }

原文地址:https://www.jb51.cc/swift/321691.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐