Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Data using popToRootViewController

So I have a basic app, here is how it works. I have a root view controller called A and a table view controller called B. And when the user selects a row in B I pop back to the root view controller A.

And what I am trying to do is to pass the data of the row that was selected as a NSString back to the root view controller A. And then use this string to "do something" depending on the string.

I have tried using the NSNotification method but then I can't use the string to do something.

Heres what I have tried:

//tableViewB.m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[[_objects objectAtIndex:indexPath.row] objectForKey:@"title"]];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//rootViewA.m
-(void)dataReceived:(NSNotification *)noti
{
     NSLog(@"dataReceived :%@", noti.object);

}
-(void)viewDidLoad {
  [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil];
}

What I am trying to do is some more like you can do when you push a viewController and use the perpareForSegue Method.

Thanks in advance for your help.


1 Answers

You're doing the right thing but with the wrong parameters. The object: param in the notification post is the sending object. There's another post method that allows the caller to attach userInfo: as follows:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // notice the prettier, modern notation
    NSString *string = _objects[indexPath.row][@"title"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData"
                                                        object:self
                                                      userInfo:@{"theString" : string }]
    [self.navigationController popToRootViewControllerAnimated:YES];
}

On the receiving end, just get the data out of the notification's user info with the same key:

-(void)dataReceived:(NSNotification *)notification {

     NSLog(@"dataReceived :%@", notification.userInfo[@"theString"]);
}
like image 183
danh Avatar answered Feb 20 '26 17:02

danh