Reputation: 7370
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:
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
Upvotes: 3
Views: 328
Reputation:
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.
Upvotes: 0
Reputation: 5182
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];
//...
}
Upvotes: 2