Swift:单例使用的一个问题

查看:71
本文介绍了Swift:单例使用的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

单例类MyObject:

class MyObject: NSObject {
    fileprivate override init() {
        super.init()
    }
    
    static let sharedInstance = MyObject()
    var myClosure: ((String) -> Void)?
}

firstController:

    func doSomething() {
        MyObject.sharedInstance.myClosure = {(s1) in
            print(s1)
            
        }
        self.navigationController?.pushViewController(SecondController(), animated: true)      
    }

secondController:

    override func viewDidLoad() {
        super.viewDidLoad()
        MyObject.sharedInstance.myClosure = {(s1) in
            print(s1)
            
        }
    }

现在我在secondController点击按钮执行:

    func doSaveAction() {
        MyObject.sharedInstance.myClosure!("123")
    }

我期望的是firstController和secondController的闭包都能响应调用事件,但结果只有secondController的闭包响应了事件,这是为什么?

解决方案

myClosure 在secondController中被被再次 ‘赋值’

这篇关于Swift:单例使用的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆