0

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。ただし、変数の値が通過していません。これが私が立ち往生している場所です。

私の変数値が通過しない理由について、誰かが解決策を考えてもらえますか?

明確にするために、行の直前に NSLog を実行して、このpostNotificationName値を表示するとself.currentScore;、予想どおり 1 が返されます。updateTheScore関数では、returns 0.

みなさん、よろしくお願いします。

4

2 に答える 2

2

予想とは異なる値が得られる理由がわかりません。たぶん、あなたがメインスレッドにいないからですか?あなたはそれをチェックすることができます[NSThread isMainThread]

実際に通知でオブジ​​ェクトを渡したい場合は、NSNotification オブジェクトの userInfo プロパティを使用できます。これが適切な方法です。NSNotificationCenter の最大の利点の 1 つは、投稿者と受信者をお互いに知らなくても、通知を投稿したり受信したりできることです。

そのような通知を投稿できます

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

そして、そのように受け取る

- (void)updateTheScore:(NSNotification *)notification
{
    NSInteger value = [[notification.userInfo objectForKey:key] intValue];
}
于 2013-05-27T12:50:25.117 に答える
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);
于 2013-05-27T12:49:59.020 に答える