๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun
article thumbnail

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

https://velog.io/@wansook0316/Notification-Center

profile

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun

@iosun

ํฌ์ŠคํŒ…์ด ์ข‹์•˜๋‹ค๋ฉด "์ข‹์•„์š”โค๏ธ" ๋˜๋Š” "๊ตฌ๋…๐Ÿ‘๐Ÿป" ํ•ด์ฃผ์„ธ์š”!

profile on loading

Loading...