2013-05-27 1 views
0

NSNotification을 사용하는 프로그램을 만들고 있는데 다른 클래스의 변수 값에 영향을 미치는 다른 클래스에서 정보를 전달할 수 있기를 원합니다.NSNotification - 다른 클래스에서 전달되지 않는 정보

categories.m 클래스 :

viewDidLoad에서 : 같은 클래스에서

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

, 내 updateTheScore 기능 :

- (void)updateTheScore:(NSNotification *)notification 
{ 
NSLog(@"Notification Received. The value of the score is currently %d", self.mainScreen.currentScore); 
[[NSNotificationCenter defaultCenter]removeObserver:self]; 
} 

그래서, 나는 다음과 같은 설정 한

있음 mainScreen.m : 일반적인 인스턴스

self.currentScore++; 
[[NSNotificationCenter defaultCenter]postNotificationName:@"TheScore" object:self]; 

점수는 내 NSLog이 수행되는 볼 수있는 프로그램이 올바르게 notification를 호출합니다 0에서 1

으로 업데이트 할 것입니다. 그러나 변수의 값이 통과하지 못하고 이것이 내가 붙어있는 곳입니다.

누군가 내 변수 값이 전달되지 않는 이유에 대한 해결책을 생각해 볼 수 있습니까?

분명히하기 위해 postNotificationName 라인 바로 앞에 NSLog를 입력하면 self.currentScore;의 값이 표시되어 예상대로 1을 반환합니다. updateTheScore 함수에서는 returns 0입니다.

미리 감사드립니다.

+0

처럼받을 수 있습니다 ... – NSDmitry

답변

2

왜 다른 값을 기대할 수 있는지 모르겠다. 어쩌면, 당신이 아니라 메인 스레드에? [NSThread isMainThread]

실제로 알림이있는 객체를 전달하려면 NSNotification 객체의 userInfo 속성을 사용할 수 있습니다. 이것을하는 적절한 방법입니다. NSNotificationCenter의 가장 큰 장점 중 하나는 게시자와 수신자가 서로 모르게 알림을 게시하고 게시 할 수 있다는 것입니다.

당신은 당신이 NSLog에 점수를 인쇄 할 곳 난 단지 참조 그

[[NSNotificationCenter defaultCenter] postNotificationName:notificationName 
                  object:self 
                  userInfo:@{key:[NSNumber numberWithInt:value]}]; 

같은 통지를 게시하고 점수를 업데이트 어디를 참조하지 않는

- (void)updateTheScore:(NSNotification *)notification 
{ 
    NSInteger value = [[notification.userInfo objectForKey:key] intValue]; 
} 
+0

Mert 님,이 문제를 완전히 해결했습니다. 많은 감사를드립니다. – user1309044

0

self.mainScreen.currentScore을 로깅합니다. 확실한 질문은 : self.mainScreen은 알림을 게시하는 동일한 개체입니까? 어쩌면 MainScreen의 인스턴스가 여러 개있을 수 있습니다 (클래스 이름으로 가정).

게시 할 때 self을 알림에 첨부 했으므로 시도해 보셨습니까?

int currentScore = (int)[[notification object] currentScore]; 
NSLog(@"Notification Received. The value of the score is currently %d", currentScore);