How can I pass NSString values from ViewController1
to ViewController2
by using notifications in iOS? I have tried:
ViewController1
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:@"test" object:nil];
}
- (void) incomingNotification:(NSNotification *)notification{
NSString *theString = [notification object];
NSLog(@"theString value=%@",theString);
}
ViewController2
- (void)viewDidLoad
{
NSString *myString=@"testing";
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object: myString];
}
It works fine while am going to ViewController2.
But I want to send values from ViewController1
to ViewController2
using these notifications. Is it possible. How?
You can use it by initializing ViewController2 in ViewController1's on button click event..Steps to invoke, 1.Create on method (say like notifRegister) in ViewController2,which initialize notification to receive dictionary value. 2.On button click event init ViewController2 and call method notifRegister 3.Then post notification in ViewController1.
Example:
- (IBAction)navigation:(id)sender {
ViewController1 *vc= [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController2"];
[vc notifRegister];
[self.navigationController pushViewController:(UIViewController*)vc animated:YES];
NSDictionary *name=[[NSDictionary alloc] initWithObjectsAndKeys:@"Tommy",@"name",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"TextChanged" object:name];
}
On ViewController2:
-(void)notifRegister
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadLabel:) name:@"TextChanged"object:nil];
}
-(void)reloadLabel:(NSNotification*)sender
{
NSLog(@"reload label called %@",sender.object);
self.labelName=[sender.object objectForKey:@"name"];
}
Here self.labelName is an NSString object...