NSNotification argument in NSNotificationCenter method is nil - ios

I have this really unexplained problem with NSNotification method.
I have been using NSNotificationCenter for a long time but i can't explain why this is happening.
My problem is this,
I have a UITableViewCell subclass where i send a NSNotificationCenter method to the UIViewController when a user taps a button in the cell.
[[NSNotificationCenter defaultCenter] postNotificationName:MOVE_TO_PROGRAM_VIEW
object:self
userInfo:#{INDEX_ROW : [NSNumber numberWithInteger:self.tag]}];
Where the self.tag is the row (for the data model in the controller).
In the controller i register for the notification in viewWillAppear: like so:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(userWantsToGoToProgramView:) name:MOVE_TO_PROGRAM_VIEW object:nil];
I also remove myself in the viewWillDisappear:
[[NSNotificationCenter defaultCenter] removeObserver:self name:MOVE_TO_PROGRAM_VIEW object:nil];
Now in the method for the notification i try to get the userInfo and the row but the notificaiton argument is nil for some reason..
- (void)userWantsToGoToProgramView:(NSNotification *)notification
{
// notification is nil here
// get the index of the video in the feed
NSDictionary *userInfo = notification.userInfo;
NSInteger videoIndex = [userInfo[INDEX_ROW] integerValue];
NSDictionary *videoData = self.feed[videoIndex];
}
Any advice of help will be appreciated
Thanks!

Related

Get command key from SKScene

I wanted to support keyboard for my SpriteKit game, but here's the problem:
We get the command keys from ViewController:
- (NSArray *)keyCommands {
return #[[UIKeyCommand keyCommandWithInput:#" " modifierFlags:0 action:#selector(fire)]];
}
But the game logic are all in SKScene, presented from the ViewController... and there are multiple SKScene... how does the scene get the command from ViewController? Or we need to do keyboard polling?
You can send message by NSNotification
Add Observer in SKScene,
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(selectorMethod:)
name: #"NOTIFICATION_NAME"
object:nil];
Post Notification form UIViewController,
NSDictionary *userInfo = #{ #"Key": #"Value" };
[[NSNotificationCenter defaultCenter] postNotificationName: #"NOTIFICATION_NAME" object:nil userInfo:userInfo];

Populate data in textfield from button action of another class

my problem is that i have a textfield on my viewcontroller which should be get filled by user and to provide options to fill the textfiled there is a arrow button front of textfield. Clicking on it open a new viewcontroller with a list of options. So when the user click on any option from that viewcontroller the data will automatically fill in that textfield and user return on previous viewcontroller. And i can not use preprefor segue in it so please provide an answer. If i am missing something let me know i ll comment or edit.
You can use NSNotificationCenter to fill back your UITextField. Add Observer to your first viewController class where you want to fill the textField. Add this lines of code in viewDidLoad-
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(fillMyTextField:) name:#"fillMyTextField" object:nil];
than add selector method in same class--
- (void)fillMyTextField:(NSNotification *)notification
{
self.myTxtField.text = (NSString *)notification.userInfo;
}
Now in your other viewController class where you select data for textField. Write the below code in method where you select your data like-
- (IBAction)selectDataAndBackToPreviosVC:(UIButton*)selectedOptionBtn {
id object=[NSString stringWithFormat:#"%#",selectedOptionBtn.titleLabel.text];
[[NSNotificationCenter defaultCenter] postNotificationName:#"fillTextField" object:nil userInfo:object];
[self.navigationController popViewControllerAnimated:YES];
}
in this I have used navigationViewController which use Push and Pop viewControllers and i have some UIButton in option selection viewController. I'm passing button title which is options to myTextField on IBAction.
In class where textfield Define Below method (add notification observer)
in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(fillTextField:)
name:#"fillTextField"
object:nil];
- (IBAction)fillTextField:(NSNotification *)sender
{
textField.text = (NSString *)notification.object
}
In Another class where u select date set below method in date selection action
[[NSNotificationCenter defaultCenter] postNotificationName:#"fillTextField" object:nil userInfo:textFieldInfo];
You can use NSNotification:
In View controller ofTextField add this
- (void) viewDidLoad
{
//Your rest of code then below statement
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveTextNotification:)
name:#"TestNotification"
object:nil];
}
- (void)receiveTextNotification:(NSNotification *)notification {
NSLog(#"%# updated", [notification userInfo]);
}
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
In View controller of Button, on button click add this:
- (IBAction)fillTextFieldAction: (id) sender {
// All instances observing the `TestNotification` will be notified
[[NSNotificationCenter defaultCenter] postNotificationName:#"TestNotification" object:self userInfo:text]; //Object here can be any changed value .
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(fillTextFieldAction:) name:#"fillTextField" object:nil];
- (IBAction)fillTextFieldAction:(NSNotification *)notification
{
textField.text = (NSString *)notification.object
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"fillTextField" object:nil userInfo:textFieldInfo];

How to send & receive data using NSNotificationCenter in iOS (XCode6.4)

I am facing an issue with NSNotificationCenter.
I am not able to send message and receive message using NSNotificationCenter in latest ios 8.4 (XCode 6.4)
Please check the following code:
1) I want to send data using first view controller to another view.
so i have written the following code in first viewcontroller:
When user btn clicked method as following :
- (IBAction)btnClicked:(id)sender
{
[self postNotification];
[self performSegueWithIdentifier:#"asGo" sender:self];
}
-(void)postNotification{
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyNotification" object:self];
}
2) In Second view controller i have added observer in ViewWillApper as following :
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(eventListenerDidReceiveNotification:)
name:#"MyNotification"
object:nil];
}
-(void)eventListenerDidReceiveNotification:(NSNotification*)txt
{
NSLog(#"i got notfication:");
}
so eventListenerDidReceiveNotification is not called while come on view.
But i am not getting above log while i come on second vc with navigation
As others have noted, NSNotificationCenter doesn't work like a post office. It only delivers notifications if someone actually listens to them at the moment they arrived. This is the reason your eventListenerDidReceiveNotification method is not being called: you add an observer in viewWillAppear, which is called after the segue (I assume that you're using segues because of the performSegueWithIdentifier method in your code) is finished, so it's definitely called after postNotification has been called.
So, in order to pass data via NSNotificationCenter you have to add an observer before you post a notification.
The following code is completely useless and unnecessarily overcomplicated, you shouldn't do anything like that, but since you keep insisting on using a scheme like this, here you go:
//Didn't test this code. Didn't even compile it, to be honest, but it should be enough to get the idea.
NSString * const SOUselessNotificationName = #"MyUselessNotification";
#pragma mark - FIRST VC
#interface SOFirstVC : UIViewController
#end
#implementation SOFirstVC
NSString * const SOasGoSegueIdentifer = #"asGo";
- (IBAction)btnClicked:(id)sender {
[self performSegueWithIdentifier:SOasGoSegueIdentifer sender:self];
}
-(void)postNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:SOUselessNotificationName object:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifer isEqualToString:SOasGoSegueIdentifer]) {
SOSecondVC *destinationVC = (SOSecondVC *)segue.destinationViewController;
[destinationVC registerToReceiveNotificationsFromObject:self];
[self postNotification];
}
}
#end
#pragma mark - SECOND VC
#interface SOSecondVC : UIViewController
-(void)registerToReceiveNotificationsFromObject:(id)object;
#end
#implementation SOSecondVC
-(void)registerToReceiveNotificationsFromObject:(id)object {
[[NSNotificationCenter defaultCenter] addObserver:self selector:(eventListenerDidReceiveUselessNotification:) name:SOUselessNotificationName object:object];
}
-(void)eventListenerDidReceiveUselessNotification:(NSNotification*)uselessNotification {
NSLog(#"I got a useless notfication! Yay!");
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#end
NSNotificationCenter basically has 3 steps
Adding Observer like [[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(open:) name:#"OpenDetail" object:nil];
Posting Notification [[NSNotificationCenter defaultCenter] postNotificationName:#"OpenDetail" object:self];
Removing Observer [[NSNotificationCenter defaultCenter] removeObserver:self name:#"OpenDetail" object:nil];
I think you are posting your notification and then later adding observer while it's vie versa. You have to add observer first then post notification.
HTH
First you have to setup the data you want to send
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:#"aKey"];
Then you post it with the data like so:
[[NSNotificationCenter defaultCenter] postNotificationName: #"MyNotification" object:nil userInfo:userInfo];
And finally you read the data off the notification:
-(void)eventListenerDidReceiveNotification:(NSNotification*)notification
{
NSLog(#"i got notification:");
NSDictionary *userInfo = notification.userInfo;
NSString *myObject = [userInfo objectForKey:#"aKey"];
}

NSNotification stops updating on any of user interface events?

I am using NSNotificationCenter to subscribe to event,
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(useNotificationWithLocation:)
name:#"somename"
object:nil];
And sending from static library,
[[NSNotificationCenter defaultCenter] postNotificationName:#"somename" object:nil userInfo:dictionary];
Everything works as expected, but when I use any of the UI event, like button click, I stop getting notification. I do not have any clue what is happening.
useNotificationWithLocation code,
-(void)useNotificationWithLocation:(NSNotification*)value
{
NSDictionary* dictionary = value.userInfo;
CLLocation *currentLoc = [dictionary valueForKey:CURRENT_LOCATION_NOTIFY];
NSLog(#"useNotificationWithLocation %#",currentLoc);
}
Please suggest what should I do about this.

NSNotificationCenter , prints memory address

I have in my app a UITableview Controller, a View Controller and I'm trying to pass NSDictionary from UITableview Controller to my ViewController, using NSNotificationCenter. So, I push a notification at my UITableview Controller and then I add an observer ,using a selector at my ViewController.The selector is called,but I have an NSLog and get memory results ,like :
ViewController: 0x8a0bcc0
I have tried to pass NSString instead of NSDictionary , but I get again memory results , and not the value of the string.
My code :
UITableView Controller
NSString *string=#"This is a test string";
[[NSNotificationCenter defaultCenter] postNotificationName: #"Update" object: string];
ViewController
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(incomingNotification:) name:#"Update" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Update" object:self];
And here is the incomingNotification selector method:
-(void) incomingNotification : (NSNotification *)notification{
NSLog(#"Trying to print : %#",[notification object]);
}
All Notifications take place at ViewDidLoad method.Thank you!
UPDATE
Finally , I quit using NSNotificationCenter and used properties to pass data ,changing a bit the inheretence from my TableViewController. No idea why Notifications did not work ,as they were supposed to. Thank you all ,very much for your suggestions and ideas :)
[[NSNotificationCenter defaultCenter] postNotificationName:#"Update" object:self]
Object means the object that generates a notification. To post parameters use another method
[[NSNotificationCenter defaultCenter] postNotificationName:#"Update" object:self userInfo:string]
If I understand correctly, UIViewController is shown after you tap a button on UITableViewController. And you if you are adding a ViewController as observer in its -viewDidLoad:, then it will be able to receive notifications only when it is loaded.
What do you need:
1) override -init or -initWithNibName: method of ViewController like this:
-(id) init
{
self = [super init];
if (self)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(incomingNotification:) name:#"Update" object:nil];
}
return self;
}
so you can be sure ViewController is observing for notifications from the beginning (well, this might be unnecessary step for your case)
2) when you push ViewController you need to send a notification after it was created, like this:
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ViewController *nextController = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:nextController animated:YES];
NSString *string=#"This is a test string";
[[NSNotificationCenter defaultCenter] postNotificationName: #"Update" object: string];
}
However, if you're trying just to send some parameters from one view controller to another, this is the wrong way. Just create a property in ViewController and in method -tableView:didSelectRowAtIndex: of UITableViewController set this property

Resources