如何使用NSNotificationCenter在类之间传递对象 - 无法传递对象

Nij*_*018 4 objective-c nsnotificationcenter ios

我的代码:

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];
Run Code Online (Sandbox Code Playgroud)

并且:

- (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;
    }];
}
Run Code Online (Sandbox Code Playgroud)

但是当键盘显示或隐藏时,这两种方法不起作用.如果我传递对象nil而不是dict,那么这两种方法是有效的.

我不知道问题出在哪里,请帮帮我,谢谢.

moh*_*acs 15

我可以看到你试图在观察者一侧发布对象.它完全相反,请参见下面的示例.

接收器类

- (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.
    }
}
Run Code Online (Sandbox Code Playgroud)

发件人类

- (void)sendNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:YOUR_DICTIONARY];
}
Run Code Online (Sandbox Code Playgroud)