ios 뽀개기/objective-c

NSNotification 예제 (자식창 닫을때 부모창도 같이 닫기)

인생여희 2019. 10. 24. 18:05
반응형

NSNotification 예제

최상위뷰가 있다.

최상위 뷰에서 부모뷰를 띄웠다. 

부모뷰에서 자식 뷰를 띄웠다.

 

이때, 자식뷰를 닫을때 부모뷰까지 같이 닫아 줘야하는 요구사항이 있다. 이럴때는 NSNotification 을 사용한다.

 

먼저 부모뷰에 NSNotification 설정과 콜백메소드(편의상 이렇게 부르겠다)를 작성해준다.

viewdidload{

    //노티피케이션 등록 - 자식창을 닫을때 이곳(부모)도 닫히게 노티 등록

    [[NSNotificationCenter defaultCenter] addObserver:self

    selector:@selector(closeViewControllerBySelf:)

        name:@"close"

      object:nil];

}

이렇게 셋팅을 해주고 호출될 메소드를 작성해준다.

//자식창 닫힐때 부모창도 같이 닫히게

-(void) closeViewControllerBySelf:(NSNotification *) notification{

    NSLog(@"부모창이 콜되었습니다.");

    NSString *message = [notification.userInfo objectForKey:@"message"];

    NSLog(@"자식창에서 던져준 메시지 :  %@", message); //취소팝업 뷰 컨트롤러에서 던진 확인용 메시지입니다

    //화면닫기

    [self dismissViewControllerAnimated:YES completion:^{

        //부모창 닫기 성공

    }];

}

이제 자식 뷰 로직을 보자.

//닫기 버튼 눌렀을때!

- (IBAction)cancelAction:(id)sender {    

    //창 닫기

    [self dismissViewControllerAnimated:YES completion:^{

        //창이 닫힐때 작성을 해주어야 한다. 위에 작성하면 이 창을 호출한 부모창은 닫히지 않는다.

        NSDictionary *userInfo = @{ @"message": @"취소팝업 뷰 컨트롤러에서 던진 확인용 메시지입니다." };

        [[NSNotificationCenter defaultCenter] postNotificationName:@"close"

                                        object:nil

                                        userInfo:userInfo];

        // [[self view] removeFromSuperview];

    }];

}

 

자식뷰에서 창이 닫힐때 NSNotificationCenter를 이용해서 postNotificationName에해당 이름을넣고 창을 닫아주면,부모창의 NSNotificationCenter메소드가 호출된다

참고:http://seorenn.blogspot.com/2014/05/cocoa-nsnotification.html

반응형