ios - 如何使用 NSNotificationCenter 在类之间传递对象 - 传递对象失败

标签 ios objective-c nsnotificationcenter

我的代码:

NSDictionary *dict = @{@"1": @"_infoView3",
                       @"2": [NSNumber numberWithFloat:_showSelectionView.frame.size.height]
                       };

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:@"UIKeyboardWillShowNotification"
                                           object:dict];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardDidHide:)
                                             name:@"UIKeyboardDidHideNotification"
                                           object:dict];

和:

- (void) keyboardWillShow:(NSNotification *)note {
    NSDictionary *userInfo = [note userInfo];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    // move the view up by 30 pts
    CGRect frame = self.view.frame;
    frame.origin.y = -kbSize.height;

    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
    }];
}

- (void) keyboardDidHide:(NSNotification *)note {

    // move the view back to the origin
    CGRect frame = self.view.frame;
    frame.origin.y = 0;

    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
    }];
}

但是当键盘显示或隐藏时,这两种方法都不起作用。 如果我传递对象 nil 而不是 dict,这两种方法就可以工作。

不知道哪里出了问题,求大神指点,谢谢

最佳答案

正如我所看到的,您正在尝试在观察者端发布对象。恰恰相反,请参见下面的示例。

接收类

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveNotification:) 
        name:@"myNotification"
        object:nil];
}

- (void)receiveNotification:(NSNotification *)notification
{
    if ([[notification name] isEqualToString:@"myNotification"]) {
        NSDictionary *myDictionary = (NSDictionary *)notification.object;
        //doSomething here.
    }
}

发送者类

- (void)sendNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:YOUR_DICTIONARY];
}

关于ios - 如何使用 NSNotificationCenter 在类之间传递对象 - 传递对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25012459/

相关文章:

ios - libiPhone-lib.a 在 Unity 构建到 xcode 后太大(大小约为 1.1G!)

iphone - 如何在我的应用程序最小化之前捕获事件?

objective-c - 在 Objective-C 中使用带有可为空字符串值的 Swift 完成 block

iPhone 应用程序崩溃 [__NSCFString objectForKey :] unrecognized selector sent to instance

ios - 调用文本字段委托(delegate)之前需要的键盘高度

ios - dispatch_queue_t 中的 "t"代表什么?

ios - 在 NSUserDefaults 中的 NSDictionary 中设置嵌套值

ios - 在 viewDidLoad 中注册通知

swift - 检查一天的变化 - 时区调整

ios - 消息发送到解除分配的实例 ARC