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)
    }




    


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值