NSNotificationAndNSNotificationCenter

KVO设计模式

能使得一个对象的改变,使另一个对象在某个时刻执行相应的代码。

与MVC模式中 model改变 从而关联view层,松耦合。

被观察对象:

let center = NSNotificationCenter.defaultCenter()

center.postNotificationName("postMyLove", object: self, userInfo: ["boy":"hxl","girl":"yyx"])

向center发出通知。

另一个swift文件中  观察者:

override func viewDidLoad() {

NSNotificationCenter.defaultCenter().addObserver(self, selector: "excute:", name: "postMyLove", object: nil)

}

func excute(nofi: NSNotification){

let info = nofi.userInfo as! [String: String]  //  userinfo:[NSobject:Anyobject]

print("i get the love",info["boy"]!,"love",info["girl"]!)

}

deinit{

NSNotificationCenter.defaultCenter().removeObserver(self)

}

观察者接收到通知并执行 selector中的代码。

简单记录一下kvo:

模型  context上下文  在被观察的属性中addObserver 

监测到变化后执行代码 

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer){

}

模型

class showKVO: NSObject{

dynamic var name: String

dynamic var num: Int

init(name:String,number: Int) {

self.name = name

self.num = number

}

deinit{

print("kvo already gone")

}

}

实例 let student = showKVO(name: "yyx", number: 1)

对两个属性增加观察者

student.addObserver(self, forKeyPath: "num", options: .Old, context: &mycontext)

student.addObserver(self, forKeyPath: "name", options: .New, context: &mycontext)

监测变化:(change是指改变之后的字典 包含 options定义的值)

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer) {

if context == &mycontext{

if let changes = change{

print("changeTheNumber\(changes)")

}

}

}

利用button改变数值触发kvo:

@IBAction func change(sender: AnyObject) {

student.num = 2

student.name = "hxl"

print(student.num)

}

你可能感兴趣的:(NSNotificationAndNSNotificationCenter)