标签:
|
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 UIKitclass 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() }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import UIKitclass 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() }} |
|
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 UIKitclass 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/4858353.html