본문 바로가기
iOS/Objective-C

NotificationCenter(Observer)

by 패쓰킴 2022. 6. 10.
728x90

노티피케이션센터는 string 키값을 이용해 여러 화면으로 noti를 보내 원하는 동작을 수행할 수 있게 해준다. 그래서 여러 화면에서 특정 액션을 캐치할 필요가 있다면 NotificationCenter 사용이 적합하다.

다만, string을 이용하면서 오탈자 발생 가능성이 있고, NotificationCenter.default에서 모든 noti가 관리되어서 딜리게이트(프로토콜)와 달리 추적이 쉽지 않다.

그래서 extenstion으로 Notification을 관리해주는 별도 클래스를 두는 것이 좋다.

 

NotificationCenter class

Notification.h

typedef enum {
    messageNoti // 간단하게 noti key도 이렇게 관리
    messageAdd,
    messageDelete,
    messageModify
} NotiType;

NS_ASSUME_NONNULL_BEGIN

@interface Notification : NSObject
+ (NSString *)name:(NotiType)type;
@end

NS_ASSUME_NONNULL_END

Notification.m

#import "Notification.h"

static Notification * instance = nil;

@implementation Notification

+ (Notification*)getInstance {
    if (instance == nil) {
        instance = [Notification new];
    }
    return instance;
}

+ (NSString *)name:(NotiType)type {
    NSString *result = nil;

    switch(type) {
        case messageNoti:
            result = @"messageNoti";
            break;
        case messageAdd:
            result = @"messageAdd";
            break;
        case messageDelete:
            result = @"messageDelete";
            break;
        case messageModify:
            result = @"messageModify";
            break;
        default:
            break;
    }
    return result;
}

@end

NotificationCenter 사용

크게 데이터에 변화를 주는 화면과 변화를 캐치하는 화면으로 나뉜다.

 

메세지작성VC.m - 데이터에 변화를 주는 화면

#import "Notification.h"

- (IBAction)saveMesaage:(UIButton*)sender {
    // messageAdd의 신호를 받는 모든 화면에 알림
    NSDictionary *dict = [NSDictionary dictionaryWithObject:[Notification name:messageNoti] forKey:[Notification name:messageAdd]];
    [NSNotificationCener defaultCenter] postNotificationName:[Notification name:messageNoti] object:nil userInfo:dict];
}

- (IBAction)modifyMesaage:(UIButton*)sender {
    NSDictionary *dict = [NSDictionary dictionaryWithObject:[Notification name:messageNoti] forKey:[Notification name:messageModify]];
    [NSNotificationCener defaultCenter] postNotificationName:[Notification name:messageNoti] object:nil userInfo:dict];
}

메세지내용보여주는VC.m - 변화를 캐치하는 화면

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiCall:) name:[Notification name:messageNoti] object: nil];
}

// notification 사용이 완료되면 항상 notification 해제를 해주어야 한다.
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)notiCall:(NSNotification*)noti {
    NSString * msg = [noti.userInfo valueForKey:[Notification name:messageNoti]];
    
    if ([msg isEqualToString:[Notification name:messageAdd]]) {
        // 원하는 작업
    } else if ([msg isEqualToString:[Notification name:messageDelete]]) {
        // 원하는 작업 
    } else if ([msg isEqualToString:[Notification name:messageModify]]) {
        // 원하는 작업
    }
}

 

기본적인 사용법 참고:

https://roniruny.tistory.com/151

https://woongsios.tistory.com/53

728x90

'iOS > Objective-C' 카테고리의 다른 글

NSString  (0) 2022.10.27
UIButton  (0) 2022.09.28
integer 값 참조 오류  (0) 2022.05.20
Extension  (0) 2022.04.25
UIView에 그라데이션 적용하기  (0) 2022.04.01

댓글