How do I access a variable in one view controller

2019-04-16 00:27发布

问题:

In my UINavtigationController application, I have a user select a value in UITableViewController and once that is done, they are sent back to a previous UITableViewController where that value must be shown. The problem I am anticipating is that once a view is "popped", I am assuming that its viewUnload is called that gets rid of the array making it unaccessible in another view controller.

Any thoughts?

回答1:

You need to pass the new value to previous controller from your didSelectRowIndex function by using anyone of the approaches

1-> Using NSUserDefault.

iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

2-> Using Delegate concept.

3-> you could also access the previous ViewController from you UINavigationController methods.



回答2:

You can access the first view controller via self.parentViewController, so it would be best to synthesize an array in the first view, then set it before you call popViewControllerAnimated: in the second. Basically it would look like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.parentViewController setNewArray:myArray];
    [self.navigationController popViewControllerAnimated:YES];
}

Just make sure you have NSArray *newArray; and @property (nonatomic, retain) NSArray *newArray specified in the first view's header file and synthesized in the implementation file



回答3:

you can use NSUserDefaults to achieve the same