swiftSwiftiOS 传值

Swift5-swift的四种传值方式

2020-05-18  本文已影响0人  Jesscia_Liu

Swift 的四种传值方式: 1.单例 2.代理 3.闭包(oc的block) 4.通知

一、单例

1.创建

class testSwiftView: NSObject {
    static let shareInstance = testSwiftView()
    func getString(){
        print("single")
    }
}

2.使用

testSwiftView.shareInstance.getString()

3.验证是否唯一

let obj = testSwiftView.shareInstance
print(Unmanaged.passUnretained(obj).toOpaque()) // 打印内存地址

二、代理

1.定义声明协议

public protocol testDelegate: AnyObject {//必须实现
    func changeString(newString: String)
}
extension testDelegate {//可选实现
    public func printString(newString: String){}
}

class testSwiftView: UIView {
    public weak var delegate: testDelegate?
    func testFun(){
        self.delegate?.changeString(newString: "hahaha")
    }
}
  1. 遵守协议,实现代理方法
class ViewController: UIViewController, testDelegate {
    func changeString(newString: String) {
        print(newString) 
    }
    func printString(newString: String) {
        print(newString)
    }
    override func viewDidLoad() {
        let obj = testSwiftView()
        obj.delegate = self
        obj.testFun()
    }
}

三、闭包 (即oc的block)

  1. 定义闭包
typealias swiftBlock = (_ str: String) -> Void
//写法2: typealias swiftBlock = (_ str: String) -> ()
class testSwiftView: UIView {
    //闭包:函数参数
    func callBackBlock(_ block: @escaping swiftBlock) {
        block(_:"闭包传值1")
    }
    
    //闭包:变量
    var callBack : swiftBlock?
    func useBlock(){
        if callBack != nil {
            callBack!("闭包传值2")
        }
    }
}
  1. 使用闭包
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let obj = testSwiftView()
        
        //函数
        obj.callBackBlock { (str) in
            print(str)
        }
        
        //参数
        obj.callBack = { (str: String)->Void in
            print(str)
            return
        }
        obj.useBlock()
    }
}

四、通知

  1. 添加通知 (用于接收通知,销毁时记得释放添加的通知)
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加通知
        NotificationCenter.default.addObserver(self, selector:#selector(test1(notification:)), name: NSNotification.Name("testnotification"), object: nil)
    }
    
    //接收通知处理方法
    @objc func test1(notification:NSNotification) -> Void {
           let userinfo = notification.userInfo as![String:AnyObject]
           
           print("这是个通知:",userinfo["通知"] as!String)
       }
    //释放移除通知
    deinit {
           NotificationCenter.default.removeObserver(self)
    }
    
}

2.发出通知

NotificationCenter.default.post(name: NSNotification.Name("testnotification"), object: self, userInfo:["通知":"通知传值"])
上一篇下一篇

猜你喜欢

热点阅读