标签:
1,通知(NSNotification)介绍
这里所说的通知不是指发给用户看的通知消息,而是系统内部进行消息传递的通知。要介绍通知之前,我们需要先了解什么是观察者模式。
在 MVC 里,观察者模式意味着需要允许 Model 对象和 View 对象进行交流,而不能有直接的关联。
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()
operationQueue =
NSOperationQueue
.mainQueue()
applicationDidEnterBackgroundObserver =
notificationCenter.addObserverForName(
UIApplicationDidEnterBackgroundNotification
,
object:
nil
})
//notificationCenter.removeObserver(applicationDidEnterBackgroundObserver)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
|
3,使用自定义的通知
--- ViewController.swift ---
--- MyObserver.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@H_664_301@
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
NSObject
var
name:
String
=
""
init
(name:
){
.
()
.name = name
.defaultCenter().addObserver(
"downloadImage:"
name:
)
}
downloadImage(notification:
) {
userInfo = notification.userInfo
as
! [
:
AnyObject
]
value1 = userInfo[
]
!
String
value2 = userInfo[
Int
sleep(3)
"\(name) 执行完毕"
)
}
deinit {
//记得移除通知监听
.defaultCenter().removeObserver(
)
}
}
|