Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass objects between classes using NSNotificationCenter - Fail to pass objects

My code:

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];

and :

- (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;
    }];
}

But those two methods is not working when the keyboard is showing up or hiding. And those two methods is working if I pass object nil, instead dict.

I don't know where is the problem, please help me , Thank you.

like image 570
Nijat2018 Avatar asked Dec 02 '22 15:12

Nijat2018


1 Answers

As I can see you are trying to post object at observer side. It is quite opposite, see the example below.

Receiver class

- (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.
    }
}

Sender Class

- (void)sendNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:YOUR_DICTIONARY];
}
like image 98
modus Avatar answered Dec 06 '22 23:12

modus