Development Tip

NSNotificationcenter의 객체 속성을 사용하는 방법

yourdevel 2020. 10. 25. 13:13
반응형

NSNotificationcenter의 객체 속성을 사용하는 방법


누군가 NSNotifcationCenter에서 객체 속성을 사용하는 방법을 보여 주시겠습니까? 내 선택기 메서드에 정수 값을 전달하는 데 사용할 수 있기를 원합니다.

이것이 내 UI보기에서 알림 리스너를 설정 한 방법입니다. 정수 값이 전달되기를 원하기 때문에 nil을 무엇으로 대체 해야할지 모르겠습니다.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];


- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

이와 같은 다른 클래스에서 알림을 발송합니다. 함수에는 index라는 변수가 전달됩니다. 알림과 함께 어떻게 든 발동하고 싶은 것은이 값입니다.

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}

object파라미터는 일반적으로 통지의 송신자를 나타낸다 self.

추가 정보를 전달 하려면 임의의 값 사전 을 사용하는 NSNotificationCenter메소드 를 사용해야 postNotificationName:object:userInfo:합니다 (자유롭게 정의 할 수 있음). 내용 NSObject은 정수와 같은 정수 유형이 아닌 실제 인스턴스 여야 하므로 정수 값을 NSNumber개체 로 래핑해야 합니다.

NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];

object속성은 이에 적합하지 않습니다. 대신 userinfo매개 변수 를 사용하려고합니다 .

+ (id)notificationWithName:(NSString *)aName 
                    object:(id)anObject 
                  userInfo:(NSDictionary *)userInfo

userInfo 보시다시피 특히 알림과 함께 정보를 보내기위한 NSDictionary입니다.

귀하의 dispatchFunction방법 대신이 같은 것입니다 :

- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}

귀하의 receiveEvent방법은 다음과 같습니다.

- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}

참고 URL : https://stackoverflow.com/questions/4312338/how-to-use-the-object-property-of-nsnotificationcenter

반응형