UINavigationControllers: How to pass value to high

2019-08-16 18:33发布

问题:

I have SendingController which push to nav stack SendingDeatilsController (which one has a TableView). User should should pick in TableView one row (it checked by Checkmark) and I would like to pass the value of this row (let it will NSString object) to the SendingController.

How can I realize this behaviour in my application? And is SendingController parent for SendingDetailController (attribute parentController of SDC refers to SC) ??

回答1:

If you want to implement this behaviour, pass the SendingDetailController a reference to the previous view controller. This way the detail view controller can send a message to the previous one on the stack.

In your SendingDetailController define a weak reference :

// in .h
SendingController *sendingController;
@property(assign) SendingController *sendingController;

// in .m
@synthesize sendingController;

-(void)tableView:(UITableView *)tableView
 didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // retrieve the string and send the message
    [sendingController didSelectString:theString];
}

Now before pushing the SendingDetailController on the stack don't forget to set its sendingController property.

// .m
// where you push the vc
if(!sendingDetailController) {
    sendingDetailController = [[SendingDetailController alloc]
                               initWithNibName:@"TheNIBName"
                                        bundle:nil];
    sendingDetailController.sendingController = self;
}
[self.navigationController pushViewController:sendingDetailController
                                     animated:YES];

and write the method that will recieve the string.

-(void)didSelectString:(NSString *)aString {
    // do anything with string
    [self.navigationController popViewControllerAnimated:YES];
}

This should do the job.



回答2:

For easy asynchronous communication between different UIViewControllers, you may want to look at NSNotification and NSNotificationCenter.

There are plenty tutorials on the web and some good answers here at SO that can show you how to do that exactly.