1. NSNotification和NSNotificationCenter
NSNotification是通過NSNotificationCenter封裝資訊來廣播給其它對象的。一個NSNotification對象包含一個name,object,和一個可選的dictionary。name是用來辨別notification的。object指消息通知發送者。dictionary值消息傳遞的資料資訊。(字典類型)
NSNotificationCenter提供一種機制,在程式中來廣播資訊。
2. 獲得消息中心
let center = NSNotificationCenter.defaultCenter()
3. 觀察者注冊消息通知
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
/**
Description:
observer:觀察者self
selector:觀察者處理消息的方法名
name:消息通知的标記名
object:消息發送者,如果為nil,預設接收所有發送者的通知
*/
NSNotificationCenter.defaultCenter().addObserver(self, selector: "printFunc:", name: "myNotification", object: nil)
return true
}
4. 發送消息通知
NSNotificationCenter.defaultCenter().postNotificationName("myNotification", object: self, userInfo: ["str":"helloworld"])
5. 移除觀察者
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self, name: "myNotification", object: nil)
}