forwarding a notification to another class
I am using this method
- (void)keyboardWillShow:(NSNotification *)notification
that is triggered when the keyboard shows.
When this method is triggered, it receives a notification that contains several parameters about the keyboard, as the animation duration, animation curve and frame. I need to forward this notification and all its parameters to another class. So, I've tried to do this inside keyboardWillShow:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"doSomething" object:notification userInfo:nil];
th开发者_如何学Ce doSomething notification runs doSomething method on another class, and it has this form:
- (void) doSomething:(NSNotification *)notification {
but when I try to read the notification values on this other class, using, for example,
myRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
I obtain zero for all values. The notification is losing its parameters and not being forwarded. How can I do that?
thanks.
It is losing all the values because you passed nil when you created the new notification! You must pass the keyboard notification's userInfo dictionary if you want this to work. So:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"doSomething" object:self userInfo:userInfo];
In this case, the object creating this notification is this object. If you want this to appear as to come from the keyboard object, then send [notification object]
for object, but I don't recommend this. Also, why not simply have the class that you want to respond to these notifications ALSO listen for keyboard notifications? Creating and sending a new notification from within the keyboard notification call-back seems kind of round-about to me. The other option is to create a delegate-style thing where the class (I am assuming a view controller or something?) actually listening for keyboard notifications then calls back a delegate object (that other class that you want to forward this info to) and passes the userInfo dictionary to it directly. So:
// Assume a proper delegate is set and it responds to - (void)doSomething:(NSDictionary*)userInfo
[delegate doSomething:userInfo]; // from within the keyboard notification
Still, I think I would just have this other class listen for keyboard notifications itself, though.
精彩评论