ViewController class creates new instance when cre

2019-09-20 10:34发布

问题:

I'm creating a TableViewController in a class named ResourcesTableViewController. I'm creating the class with:

ViewController.h:

@interface ViewController : UIViewController {
    ResourcesTableViewController *resourceTableViewController;

ViewController.m:

resourceTableViewController = [[ResourcesTableViewController alloc] initWithStyle:UITableViewStylePlain];
[resourceTableViewController setTableViewObject:localObject];

Now I can work with it and I can call

NSLog(@"%@ %@",resourceTableViewController,[resourceTableViewController tableViewObject]);

at several parts in my ViewController.m with (as expected) the same output

<ResourcesTableViewController: 0x749f1c0> tableViewObjectContent

. For switching on the new TableView I created in the storyboard a button with the popover to the new view (as triggered segue). But as soon as the button is pressed and the view shall appear, it creates a new instance. Curiously I put in the viewDidLoad of my class ResourcesTableViewController:

NSLog(@"viewDidLoad: %@: %@", self, self.tableViewObject);

and it is returning

<ResourcesTableViewController: 0x74bbcd0>: (null)

. Another memory adress, another instance. Not the instance I worked with before and absolutely not the instance to which I gave that tableViewOject. How can I call the view from that instance belonging to the resourceTableViewController I created and worked with? I still can access that "old" instance through communicating with the object resourceTableViewController but the created view is another one of that type that certainly doesn't make use from the object I gave to the first one.

回答1:

How to show the table view depends on how you want to show it, and what is on the screen before that. Normally, you would use a segue to transition from the current controller (the one that you button is in) to the table view. To do that you could use performSegueWithIdentifier:sender: where the identifier parameter is a name you give to the segue in IB. But you can do it with no code at all by control dragging from the button in your one view to the table view controller's view and choosing modal for the type of segue -- then, a button click will cause that table view to appear on screen.

You shouldn't alloc init it at all in your code if you're using a storyboard -- the segue instantiates the new view controller for you.