Search code examples
iphoneiosnsnotificationcenter

nsnotification trouble


So I have a method:

-(void)didLoginWithAccount(MyAccount *)account

And I added an observer to this method like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLoginWithAccount:)];

And my question is, when I post Notification, how can I pass a MyAccount object?


Solution

  • When you get a notification callback, the notification object is passed, and not the object explicitly.

    Step 1, Register:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLoginWithAccount:) name:@"MyCustomNotification" object:nil];
    

    Step 2, Post:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyCustomNotification" object:myAccount]; 
    

    Step 3, Recieve:

    - (void)didLoginWithAccount:(NSNotification *)notification {
        MyAccount *myAccount = (MyAccount *)[notification object];
    }