Search code examples
objective-cnsnotifications

Passing ivar through NSNotificationCenter


I'm study about NSNotificationCenter. Here is my code

Observer.m

//note init method is not complete here

    -(id) init
    {
     [[NSNotificationCenter defaultCenter] 
             addObserver:self 
             selector:@selector(reciveTestNotification:) 
             name:@"TestNotification" object:nil];

    }

    -(void)reciveTestNotification:(NSNotification *)notification
    {
        if([[notification name] isEqualToString:@"TestNotification"])
        {
            NSLog(@"Succesfuly received the test notification");
        }
    }

Osender.m

-(void)reciveTestNotification:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"TestNotification"])
    {
        NSLog(@"Succesfuly received the test notification");
    }
}

I think that I undestand how NSNotification works, but how to pass ivar via NSNotification ?

Lets say Osender.h have this code

Osender.h

@interface Osender : NSObject
{
  IBOutlet UITextField *txt;
}

@property (nonatopic, copy) IBOutlet (UITextField *) *txt

How to notify reciveTestNotification and pass data to it when user type or change something on txt ?


Solution

  • NSNotification class has a property for additional data that you might want to send with your notification, userInfo.

    You post it like this:

    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:txt forKey:@"textField"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self userInfo:userInfo]
    

    And get it like this:

    - (void)reciveTestNotification:(NSNotification *)notification
    {
        UITextField *textField = [notification.userInfo objectForKey:@"textField"];
    }
    

    Now textField has the reference to your UITextField.