Question

In my Class X I post a Notification like this:

[[NSNotificationCenter defaultCenter] addObserver:viewController 
                                             selector:@selector(doThis:) 
                                                 name:@"myNotification" 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:nil];

In my Class Y I recieve it like this:

- (void) doThis: (NSNotification *) notification {
NSLog(@"It works.");
[uiTextView resignFirstResponder]; }

The console shows the NSLog message but my UITextView does not hide its keyboard. (In e.g. viewDidLoad the resignFirstResponder/becomeFirstResponder works.)

Is there any special thing I need to do?

Was it helpful?

Solution

As Conrad says, observers should be added and removed by themselves...

Use the best practice to define the name of the notifications as static constants like follows:

static NSString *const kMyNotification = @"myNotification";

Why? because there is a risk that both @"myNotification" might be two different objects and then the notificationName is different and you won't receive the notification. Since I always declare them as static constants I have never had issues with NSNotifications.

Then use it like this:

To register the observer

[[NSNotificationCenter defaultCenter] addObserver: self 
                                         selector: @selector(doThis:) 
                                             name: kMyNotification 
                                           object: nil];

To post the notification

[[NSNotificationCenter defaultCenter] postNotificationName: kMyNotification 
                                                    object: nil];

To remove the observer:

[[NSNotificationCenter defaultCenter] removeObserver: self];

OTHER TIPS

FWIW, in most, but not all, cases, observers should be added and removed by the observer itself, not by a separate object. (What happens if the observer goes away before the separate object, and fails to have the observer properly removed? Or vice-versa? It makes it all too easy to either leak observers or crash on notifications to deallocated objects.)

Anyhow, first thing's first: have you verified that uiTextView is not nil and points at the first responder? I rather suspect that uiTextView is not what you think it is.

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