swift--四种传值(代理、闭包、属性、通知)

单例

  • 创建swift文件不做任何继承
class TheOneAndOnlyKraken {
    // 存储属性
    var name : String?
    var age : Int = 0
    
    static let sharedInstance = TheOneAndOnlyKraken()
    // 防止外部调用
    private init() {} //This prevents others from using the default '()' initializer for this class.
}
  • 外部访问
TheOneAndOnlyKraken.sharedInstance

代理传值

  • B需要代理,声明以及声明方法func eatMany(food1: String) -> Void
protocol EatFoodDelegate {
    func eatMany(food1: String) -> Void
}
  • A遵循代理并实现方法

// 第一种设置代理方式
extension ViewController : EatFoodDelegate{
    func eatMany(food1 : String) -> Void {
        print(food1)
    }
}

// 第二种设置代理方式, 逗号 + 代理协议
// class ViewController: UIViewController, EatFoodDelegate 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("触摸屏幕")
        
        let vcOne = TestOne()
        // 设置代理
        vcOne.delegate = self
        vcOne.strBlock = {(str1 : String, str2 : String) -> Void in
            print(str1 + str2)
        }
        self.present(vcOne, animated: true) {
            print("跳转完成")
        }
        
    }

闭包传值

  • 回调到控制器A
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("触摸屏幕")
        
        let vcOne = TestOne()
        // 实现闭包 处理回调
        vcOne.strBlock = {(str1 : String, str2 : String) -> Void in
            print(str1 + str2)
        }
        self.present(vcOne, animated: true) {
            print("跳转完成")
        }
        
    }

  • 控制器B
  • 声明闭包类型
  • 两个字符串参数, 返回空类型 ? 延迟初始化
var strBlock : ((_ str1 : String, _ str2 : String) -> Void)?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.dismiss(animated: true) {
//            print("控制器消失了")
//        }
    // 对于当前没有进行初始化的对象选择了optional 即 ? 延迟初始化,需要解包时
    // ! 感叹号解包如果对象为空nil Unexpectedly found nil while unwrapping an Optional value
    // ? 问号解包 对象为空不崩溃 -建议用?
        strBlock?("hello", "world")
        let dic = ["name" : "张三", "age" : 18] as [String : Any]
        NotificationCenter.default.post(name : NSNotification.Name.init(rawValue: "h"), object: dic)
    }

发送通知

  • 注册通知 & 接收通知
  • 方法必须是oc方法 @objc前缀修饰
  • 通知名字NSNotification.Name(rawValue: "h")
// 添加通知实现同时方法
override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.hello), name: NSNotification.Name(rawValue: "h"), object: nil)
    }
    
    @objc func hello() -> Void{
        print("hello")
    }

  • 发送通知
  • 通知名字NSNotification.Name.init(rawValue: "h")
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.dismiss(animated: true) {
            print("控制器消失了")
        }
        
        NotificationCenter.default.post(name : NSNotification.Name.init(rawValue: "h"), object: nil)
    }

  • 移除通知

deinit {
        NotificationCenter.default.removeObserver(self)
    }

原文地址:https://www.cnblogs.com/adampei-bobo/p/8954042.html