2013-05-27 39 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]; 

在通常情況下的得分將更新從0到1

程序將正確調用notification,因爲我可以看到我正在執行NSLog。但是,變量的值沒有通過,這就是我卡住的地方。

任何人都可以請考慮一個解決方案,爲什麼我的變量值不通過?

爲了澄清,如果我在postNotificationName行之前做了一個NSLog,以顯示self.currentScore;的值,則返回1,如預期的那樣。在updateTheScore功能,它returns 0

在此先感謝大家。

+0

我沒有看到你更新得分,我只看到您打印比分追成NSLog的... – NSDmitry

回答

2

我不知道爲什麼你會得到另一個值,然後預期。也許,因爲你不在主線上?你可以用[NSThread isMainThread]

檢查它其實如果你想傳遞一個帶通知的對象,你可以使用NSNotification對象的userInfo屬性。這是做這件事的正確方法。 NSNotificationCenter的最大優點之一是,您可以發佈,接收通知,而無需知道海報和接收器。

您可以發佈通知一樣,

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

而且接收到類似

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

謝謝梅特,完全解決了這個問題 - 非常感謝! – 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); 
相關問題