iOS
[iOS] NotificationCenter ๋์ ๋ฐฉ์๊ณผ ํ์ฉ ๋ฐฉ์์ ๋ํด ์ค๋ช ํ์์ค.
iosun
2023. 3. 31. 20:32
NotificationCenter๋?
- observer(๊ด์ฐฐ์)์๊ฒ ์ ๋ณด๋ฅผ ์ ๋ฌํด์ฃผ๋ ์๋ฆผ ๋ฐ์ก ๋ฉ์ปค๋์ฆ
์ธ์ Notification ์ผํฐ๋ฅผ ์ฌ์ฉ?
- ์ฑ ๋ด์์ ๊ณต์์ ์ธ ์ฐ๊ฒฐ์ด ์๋ ๋ ๊ฐ ์ด์์ ์ปดํฌ๋ํธ๋ค์ด ์ํธ์์ฉ์ด ํ์ํ ๋
- ์ํธ์์ฉ์ด ๋ฐ๋ณต์ ์ผ๋ก ๊ทธ๋ฆฌ๊ณ ์ง์์ ์ผ๋ก ์ด๋ฃจ์ด์ ธ์ผ ํ ๋
- ์ผ๋๋ค ๋๋ ๋ค๋๋ค ํต์ ์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
1. Observer(๊ด์ฐฐ์) ๋ฑ๋ก
NotificationCenter.default.addObserver(
self,
selector: #selector(scrollToBottom), // ์๋ฆผ์ ๋ฐ์ ๋ ์ํํ action
name: NSNotification.Name("TestNotification"),
object: nil
)
- ์๋ฆผ์ ๋ฐ๊ณ ์ถ์ ๋ถ๋ถ์ observer๋ฅผ ๋ฑ๋กํ๋ค.
2. ์๋ฆผ ๋ฐ์ก
NotificationCenter.default.post(
name: NSNotification.Name("TestNotification"),
object: nil
)
- observer์๊ฒ ์๋ฆผ์ ๋ฐ์กํ๋ค. ์ด๋ object์ ๋ฐ์ดํฐ๋ ํจ๊ป ์ ๋ฌํ ์ ์๋ค.
3. Observer ์ ๊ฑฐ
NotificationCenter.default.removeObserver(
self,
name: NSNotification.Name("TestNotification"),
object: nil
)
- observer๋ฅผ ์ ๊ฑฐํ์ง ์์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ์ ๊ณ์ ๋จ์์๊ฒ ๋๋ฌธ์ removeํด์ค๋ค.
+extension์ ํ์ฉํ์ฌ NotificationName ๊ด๋ฆฌ
extension Notification.Name {
static let testNotification = Notification.Name("TestNotification")
}
NotificationCenter.default.post(
name: .testNotification,
object: nil
)
- Notification.Name ์๊ฒ ์ต์คํ ์ ์ ๋ถ์ฌ์ฃผ๋ฉด ์ฝ๋๊ฐ ๊ฐ๊ฒฐํด์ง๊ณ ํด๋จผ ์๋ฌ๋ฅผ ์ค์ผ ์ ์๋ค.
์ฐธ๊ณ
https://developer.apple.com/documentation/foundation/notificationcenter
NotificationCenter | Apple Developer Documentation
A notification dispatch mechanism that enables the broadcast of information to registered observers.
developer.apple.com
https://velog.io/@doyun/Notification-Center
Notification Center
Notificaton Center๋ ๋ฑ๋ก๋ event๊ฐ ๋ฐ์ํ๋ฉด ๋ฑ๋ก๋ observer์ ์ ๋ณด๋ฅผ ์๋ฆฌ๋ ์ญํ ์ ํ๋ค Observers ๋ฑ๋ก
velog.io