我正在构建一个利用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 :(得分: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];
}
答案 1 :(得分: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);