pass NSString variable to other class with NSNotification

15,617

In sender class you can post a notification with an object with something like this:

[[NSNotificationCenter defaultCenter] postNotificationName: NOTIFICATION_NAME object: myString];

The listener or receiver class has to register for the notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:NOTIFICATION_NAME object:nil];

The method incomingNotification is:

- (void) incomingNotification:(NSNotification *)notification{
   NSString *theString = [notification object];
   ...
}

EDIT

When you post the notification from "ViewController", is "ViewController2" loaded?

Share:
15,617
Niels Sønderbæk
Author by

Niels Sønderbæk

Updated on June 11, 2022

Comments

  • Niels Sønderbæk
    Niels Sønderbæk about 2 years

    I want to pass a NSString from one class to another class and add that NSString to an NSMutableArray in my second class. I'm believe i can use NSNotification for this, but i don't know how to pass an variable over notification. My code would something like this:

    //class1.h

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    
    @property(strong,nonatomic)NSString *variableString;
    
    @end
    

    //class1.m

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    @synthesize variableString = _variableString;
    
    - (void)viewDidLoad
    {
    [super viewDidLoad];
    [self setVariableString:@"test"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName: @"pasteString" object: _variableString];
    
    // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)viewDidUnload
    {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    }
    
    @end
    

    //class2.h

    #import <UIKit/UIKit.h>
    
    @interface ViewController2 : UIViewController
    
    @property(strong,nonatomic)NSMutableArray *arr;
    
    @end
    

    //class2.m

    #import "ViewController2.h"
    
    @interface ViewController2 ()
    
    @end
    
    @implementation ViewController2
    
    @synthesize arr = _arr;
    
    
    - (void)viewDidLoad:(BOOL)animated   
    {
    [super viewDidLoad];
    if(_arr == nil)
    {
        _arr = [[NSMutableArray alloc]init];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:@"pasteString" object:nil]; 
    // Do any additional setup after loading the view.
    }
    
    - (void) incomingNotification:(NSNotification *)notification{
    NSString *theString = [notification object];
    [_arr addObject:theString];
    }
    
    @end