Notification observer 사용하기

-- iOS (iPhone) 2015. 3. 2. 08:20
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
이벤트 방식으로 어떤 액션이 발생했을 때 특정 기능을 실행하고 싶을 때 필자는 Notification을 자주 사용한다.
Notification은 소스 어디에 있더라도 사용이 가능하기 때문에 강력하고 편리하다.

먼저 아래와 같이 Notification을 선언한다.

[[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(eventFunction:)

                                                 name:@"EventName"

                                               object:nil];


name: Event가 발생하면  selector: eventFunction()을 실행하라는 것으로 선언 후 같은 클래스에 selector를 생성한다.

- (void) eventFunction: (NSNotification *) notification

{

    // 이벤트가 발생했을 때 수행할 코드

}


마지막으로 소스의 어디서든지 이벤트를 발생시키면 위의 정의된 selector가 실행되게 된다.

[[NSNotificationCenter defaultCenter] postNotificationName:@"EventName"

                                                                object:self

                                                              userInfo:nil];

posted by 어린왕자악꿍