Reputation: 317
I am building a program that utilises NSNotification
as I want to be able to pass information through from another class that is going to affect the value of variables in a different class.
So, I have set up the following:
categories.m
class:
In viewDidLoad
:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheScore:)name:@"TheScore" object:nil];
in the same class, with my updateTheScore
function:
- (void)updateTheScore:(NSNotification *)notification
{
NSLog(@"Notification Received. The value of the score is currently %d", self.mainScreen.currentScore);
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
In mainScreen.m
:
self.currentScore++;
[[NSNotificationCenter defaultCenter]postNotificationName:@"TheScore" object:self];
The score in a usual instance would update from 0 to 1.
The program will call the notification
correctly, as I can see my NSLog
being performed. However, the value of the variable is not passing through, and this is where I am stuck.
Can anyone please think of a solution as to why my variable value is not passing through?
To clarify, if I do an NSLog right before the postNotificationName
line to show me the value of self.currentScore;
this returns 1, as expected. In the updateTheScore
function, it returns 0
.
Thanks in advance to everyone.
Upvotes: 0
Views: 110
Reputation: 6065
I do not know why you get another value then expected. Maybe, because your not on main thread? you can check it with [NSThread isMainThread]
Actually if you want to pass an object with notification, you can use userInfo property of NSNotification object. It is the proper way of doing this. One of the best advantage of NSNotificationCenter is, you can post, receive notifications without knowing poster and receiver eachother.
You can post notification like that
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName
object:self
userInfo:@{key:[NSNumber numberWithInt:value]}];
And receive like that
- (void)updateTheScore:(NSNotification *)notification
{
NSInteger value = [[notification.userInfo objectForKey:key] intValue];
}
Upvotes: 2
Reputation: 13378
You are logging self.mainScreen.currentScore
. The obvious question is: Is self.mainScreen
the same object that posts the notification? Maybe you have several instances of MainScreen
(assuming that this is the name of your class).
Since you are attaching self
to the notification when you post it, have you tried this?
int currentScore = (int)[[notification object] currentScore];
NSLog(@"Notification Received. The value of the score is currently %d", currentScore);
Upvotes: 0