这里所说的通知不是指发给用户看的通知消息,而是系统内部进行消息传递的通知。要介绍通知之前,我们需要先了解什么是观察者模式。
观察者模式 (Observer):指一个对象在状态变化的时候会通知另一个对象。参与者并不需要知道其他对象的具体是干什么的 。这是一种降低耦合度的设计。常见的使用方法是观察者注册监听,然后在状态改变的时候,所有观察者们都会收到通知。
Cocoa 使用两种方式实现了观察者模式: 一个是 Key-Value Observing (KVO),另一个便是本文要讲的Notification。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() let notificationCenter = NSNotificationCenter .defaultCenter() let operationQueue = NSOperationQueue .mainQueue() let applicationDidEnterBackgroundObserver = notificationCenter.addObserverForName( UIApplicationDidEnterBackgroundNotification , object: nil , queue: operationQueue, usingBlock: { (notification: NSNotification !) in print ( "程序进入到后台了" ) }) //如果不需要的话,记得把相应的通知注册给取消,避免内存浪费或奔溃 //notificationCenter.removeObserver(applicationDidEnterBackgroundObserver) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } |
3,使用自定义的通知
--- ViewController.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import UIKit class ViewController : UIViewController { let observers = [ MyObserver (name: "观察器1" ), MyObserver (name: "观察器2" )] override func viewDidLoad() { super .viewDidLoad() print ( "发送通知" ) NSNotificationCenter .defaultCenter().postNotificationName( "DownloadImageNotification" , object: self , userInfo: [ "value1" : "hangge.com" , "value2" : 12345]) print ( "通知完毕" ) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } |
--- MyObserver.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import UIKit class MyObserver : NSObject { var name: String = "" init (name: String ){ super . init () self .name = name NSNotificationCenter .defaultCenter().addObserver( self , selector: "downloadImage:" , name: "DownloadImageNotification" , object: nil ) } func downloadImage(notification: NSNotification ) { let userInfo = notification.userInfo as ! [ String : AnyObject ] let value1 = userInfo[ "value1" ] as ! String let value2 = userInfo[ "value2" ] as ! Int print ( "\(name) 获取到通知,用户数据是[\(value1),\(value2)]" ) sleep(3) print ( "\(name) 执行完毕" ) } deinit { //记得移除通知监听 NSNotificationCenter .defaultCenter().removeObserver( self ) } } |
运行结果如下:
(通过运行可以看出,通知发送后的执行时同步的,也就是观察者全部处理完毕后,主线程才继续往下进行。)
Swift - 使用NSNotificationCenter发送通知,接收通知
原文:http://www.cnblogs.com/Free-Thinker/p/5090806.html