Swift回调及notifition消息机制

Swift的delegate和notifition机制 文件kvoDemo.swift import Foundation @objc // 需要打开objc标识,否则@optional编译出错 //协议,,类似java的接口 定义这个接口,里面定义方法 protocol kvoDemoDelegate { func willDoSomething() optional func didDoSomething() //可选实现,} //初始化全局变量notifition的名字 let ntfname = "test_notification" class kvoDemo : NSObject //不写NSObject认就是从NSObject来的 { //声明这个接口为delegate var delegate: kvoDemoDelegate! override init() { } //定义一个方法执行协议的方法 func doSomething() { if let _ = self.delegate { delegate!.willDoSomething() } for _ in 1...5 { print("i'm doing Now,don't touch me,please.") } if let _ = self.delegate { delegate!.didDoSomething!() } } //发送notifition消息方法 func notificationPost() { let ntf = NSNotificationCenter.defaultCenter() ntf.postNotificationName(ntfname,object :nil,userInfo:nil) } deinit { } } 第二个文件ViewController.swift import UIKit //实现协议delegate class ViewController: UIViewController,kvoDemoDelegate{ //实现接口必须实现的方法,里面写方法的实现 //delegate func willDoSomething() { print("i will do it.") } func didDoSomething() { print("i had do it.") } //监听notifition发出的消息事件的方法 //notification func onRecviceNotification(notification:NSNotification) { print("Recevice notification \(notification)") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. //实例化kvoDemo类 let kvo = kvoDemo() //绑定 这里是比java回调中多出来的一步貌似 kvo.delegate = self //执行kvo中定义的方法方法中间就会执行到协议中的方法,然后就会执行本类中实现的协议的方法 kvo.doSomething() //注册notifition,监听 let ntf = NSNotificationCenter.defaultCenter() //接受到消息就会执行方法onRecviceNotification ntf.addobserver(self,selector:"onRecviceNotification:",name :ntfname,object : nil) //发送notifition消息 kvo.notificationPost() //取消观察者的身份 ntf.removeObserver(self) } }

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...