2013년 4월 13일 토요일

iOS에서 broadcasting 하는 방법.

iOS의 어느곳에서든지 broadcast 메세지를 보낼 수 있다. 메세지를 보낼때는 이름(유일하게 구분이 되어야 함)을 정의하게되고, 그 broadcast message를 받고 싶은 곳에서는 notification센터에 같은 이름으로 observer 등록하면 받을 수 있다.

아래 예는 sender클래스가 로그아웃 메세지를 broadcasting하고, receiver클래스에서 그 broadcast message를 받아서 처리하는 간단한 예제이다.
broadcasting의 장점은 거미줄 같은 객체간의 상호 의존성을 줄일 수 있다는 것이다. 그렇지만 broadcasting을 남발하게 되면 오히려 프로그램의 복잡성을 키울 수 있다.
따라서, 적절한 곳에 적절히 사용해야 한다.



//sender.m
- (IBAction)touchedLogoutButton:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:UserNotificationHttpRequestLogout object:self];
}





//receiver.m
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doLogout:) name:@"notification_logout" object:nil];
}

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"notification_logout" object:nil];
[super dealloc];
}

- (void)doLogout:(NSNotification *)notification
{
//로그아웃 처리
}

댓글 1개:

  1. NSString *const UserNotificationHttpRequestLogout = @"UserNotification_Logout";

    답글삭제