Question

I seem to be stuck on NSNotification for some reason.

I am posting a notification in a IBAction button method. When the user taps that button, I want to be notified about it so I can set a text in a text field. Without them tapping the button, the NSString would still be nil - which is why I need to know when they do it.

So in the button method I have this:

- (IBAction)suggestionsButton:(UIButton *)sender {

    self.usernameSelected = sender.titleLabel.text;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UserTappedButton" object:self];
}

This is in a UITableviewCell class.

I then add the observer in the view controller that is concerned with this action:

 (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userPickedAuserNameFromSuggestion:) name:@"UserTappedButton" object:nil];
}

Things I have checked:

  1. That the observer method is called first before post method (It is )
  2. That the name is correct on both methods
  3. That the selector signature is correct

Looked at a few SO answers as well and hasn't helped.

Is there something I am missing here guys?

*UPDATE *

Sorry - here is the method I want called:

-(void)userPickedAuserNameFromSuggestion: (NSNotification *)notification
{
    NSLog (@"Selected Username: %@", self.usernameCell.usernameSelected);

}

However its not being called

Was it helpful?

Solution

Put -addObserver: in viewDidAppear and -removeObserver: in viewDidDisappear

- (void)viewDidAppear:(BOOL)animated
{
    //...
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(userPickedAuserNameFromSuggestion:)
                                                 name:@"UserTappedButton"
                                               object:nil];
    //...
}

- (void)viewDidDisappear:(BOOL)animated
{
    //...
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"UserTappedButton"
                                                  object:nil];
    //...
}

OTHER TIPS

I think your Notification observer is not released correctly, you need to do this:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UserTappedButton" object:nil];

in dealloc function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top