티스토리 뷰

Swift&IOS

NotificationCenter

밀쿄 2019. 10. 1. 16:36

안녕하세요 밀쿄입니다,

오늘은 NotificationCenter에 대해서 알아봅시다.

사실 제가 개발하면서 종종 쓰는데 제대로 정리해본적이 없어서 제대로 정리해보고자 합니다

늘 깔고가는 애플문서는 여기입니다.

https://developer.apple.com/documentation/foundation/notificationcenter

 

NotificationCenter - Foundation | Apple Developer Documentation

Creates a notification with a given name, sender, and information and posts it to the notification center.

developer.apple.com

등록 된 observers에게 정보를 broadcast 할 수있는

notification 발송 메커니즘 정도로 해석 되네요

저 말을 그림으로 해석해봤습니다

 

이거 보면서 드는 생각이

어떤 한 객체에서 발생한 노티피케이션을

다른 객체에서 받을 수 있겠단 생각이 드네요.

 

사실 이런 역할을 하는 놈이

하나 더 있죠?

Delegate라고...

 

Delegate는 지정된 객체와만 상호작용할 수 있지만

NotificationCenter는 어느 객체든지 상관없이

서로 상호작용을 할 수 있습니다.

 

자 그러면 애플 문서를 조금 더 읽어봅시다.,,,

객체는

 addObserver (_ : selector : name : object :) 또는 

addObserver (forName : object : queue : using :) 

메소드를 사용하여 Notification (NSNotification 객체)을 수신하도록 NotificationCenter에 등록 

. 객체가 Observer로 자신을 추가하면 수신 할 알림을 지정

따라서 객체는 여러 가지 다른 Notification에 대한 Observer로 

자신을 등록하기 위해이 메서드를 여러 번 호출 가능

 

말로만 들으니 참 어렵네요

 

쉽게 생각하면

1) Event를 발생시키는 객체에서

 Event를 NotificationCenter에 등록을 하면

 2) 그 이벤트가 발생하면 특정 액션을 취할 객체에서 Observer로 등록

그런 메커니즘입니다.

 

이제 코드를 보겠습니다

는 뭘 해볼껀지부터 적어보겠습니다

 

세번째에 있는 텍스트 필드에 무언가 입력하면

두번째에 있는 라벨이 바뀔게 할껍니다.

 

델리게이트로도 처리할 수 있지만

전 노티피케이션으로 할껍니다.

( 노티피케이션 글이니까요 )

 

텍스트 필드를 IBAction을 따줍니다.

저는 이렇게 했습니다.

아 물론 이름은 실제론 저렇게 안했습니다

 

https://developer.apple.com/documentation/foundation/notificationcenter/1410608-post

 

post(name:object:userInfo:) - NotificationCenter | Apple Developer Documentation

Instance Method post(name:object:userInfo:) Creates a notification with a given name, sender, and information and posts it to the notification center. DeclarationParametersaNameThe name of the notification.anObjectThe object posting the notification.aUserI

developer.apple.com

노티피케이션은 이렇게 작성하는 군요

이름(name),

보내는 객체,(oject)

알림에 대한 Optional 정보(userInfo)

 

쉽게 생각하면

우리가 편지보낼 때

제목 쓰고 보내는사람 쓰고  받는사람 쓰고 내용 쓰고하는데

이 편지(노티피케이션)은 불특정 개인이나 다수에게 간다고 생각하면 이해가 좀 될까요?

 

다시 얘기하면

제목만 적어서 보낼 수도 있고

( 내용없는 빈편지도 있으니까요 )

제목 + 보내는 사람만 적어서 보낼 수도 있고

( 역시 내용없는 빈편지도 있으니까요 )

제목+ 내용만 적어서 보낼 수도 있는 거죠

 

자 그러면 한 번 작성해보겠습니다.

전 이렇게 작성했습니다..

 

object에도 실을수 있지만

userIntfo에 실었습니다.

 

object는 observer에서 보낸 객체 기준으로 필터링 할 때

보통사용한다고하는데 바로 밑에 보겠습니다

 

https://developer.apple.com/documentation/foundation/notificationcenter/1415360-addobserver

 

addObserver(_:selector:name:object:) - NotificationCenter | Apple Developer Documentation

Instance Method addObserver(_:selector:name:object:) Adds an entry to the notification center's dispatch table with an observer and a notification selector, and an optional notification name and sender. DeclarationParametersobserverObject registering as an

developer.apple.com

observer -> 관찰자로 등록할 객체 

aSelector

-> 노티피케이션이 왔을 때 실행할 액션

-> 지정된 메소드에는 하나의 인수: NSNotification 존재필수

aName

-> 노피티케이션 이름

-> nil일 경우 림 센터는 NotificationCenter 이름을 사용하여 

관찰자에게 전달할지 여부를 결정하지 않습니다.

anObject

-> 아까말한 필터링용

 

어려운설명 다 빼고 축약한 내용입니다.

 

쉽게 생각하면

이름이랑 노티피케이션이 오면 그걸 받을 함수가 있으면 된다는것 같네요

 

저는 이렇게 작성했습니다.

 

끝입니다.

실행해보시면 잘될껍니다.

'Swift&IOS' 카테고리의 다른 글

iOS13 바뀐 UIModalPresentationStyle에 관해서..  (0) 2019.10.02
다시 써보는 CoreData  (0) 2019.10.02
@discardableResult  (0) 2019.09.24
KVO로 MVVM을 짜본다면?  (0) 2019.09.09
UITableView에서 MVVM을 어캐 적용하면 좋을까?  (0) 2019.09.06
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함