A few observations:
The recommended pattern for a singleton object would be as follows. dispatch_once makes sure the class is initialised once in a thread-safe way, and the static variable isn't visible outside. And it's standard GCD, so no need to know about low level details of Objective-C.
+ (KeyboardStateListener *)sharedInstance
{
static KeyboardStateListener* shared;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[KeyboardStateListener alloc] init];
// Other initialisations
});
return shared;
}
Usually you don't want to know just whether the keyboard is visible or not, but how big it is. Keyboards don't all have the same size. iPhone keyboards are smaller than iPad keyboards. So you'd want another property @property (readonly, nonatomic) CGRect keyboardRect;
which is set in the noticeShowKeyboard: method like this:
NSValue* value = notification.userInfo [UIKeyboardFrameEndUserInfoKey];
_keyboardRect = value.CGRectValue;
Important to notice that the rectangle is in UIWindow coordinates and doesn't respect screen rotation. So the caller would convert that rectangle by calling
KeyboardStateListener* listener = [KeyboardStateListener sharedInstance];
CGRect windowRect = listener.keyboardRect;
CGRect viewRect = [myView convertRect:windowRect fromView:self.window];
If the user rotates the screen while the keyboard is visible, the app will be told that the keyboard is hidden, then shown again. When it is shown, other views are most likely not rotated yet. So if you observe keyboard hide/show events yourself, convert the coordinates when you actually need them, not in the notification.
If the user splits or undocks the keyboard, or uses a hardware keyboard, the notifications will always show the keyboard as hidden. Undocking or merging the keyboard will send a "keyboard shown" notification.
The listener must be initialised while the keyboard is hidden, otherwise the first notification will be missed, and it will be assumed that the keyboard is hidden when it's not.
So it is quite important to know what you actually want. This code is useful to move things out of the way of the keyboard (with a split or undocked keyboard, that's the responsibility of the user). It doesn't tell you whether the user can see a keyboard on the screen (in case of a split keyboard). It doesn't tell you whether the user can type (for example when there is a hardware keyboard). Looking at other windows doesn't work if the app creates other windows itself.