简体   繁体   中英

Using one instance of a viewController class in Storyboard

I am writing an iOS7 app in Xcode 5 with storyboards. In a part of the app, I need three screens that shared the same viewController class. These screens are UIViewControllers . I use a UISegmentControl to go from screen to screen based on conditions. I disabled the control if the user had not completed certain steps.

I used a BOOL value check if certain steps had been completed and set its value to YES / NO.

The problem is when I want to go back to the last screen - I am getting a new instance of my viewController class. This has two problems:

  1. Memory grows each time the user goes between the two views
  2. BOOL value and all other properties are nil when new instance loads.

In my segment control this is how I get to the views:

-(void)segmentcontrol:(UISegmentedControl *)segment
{

    if (segment.selectedSegmentIndex == 0)
        {

   self.viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"stepOne"];
        [self presentViewController:self.viewController animated:NO completion:nil];
        }
    else if (segment.selectedSegmentIndex == 1 ){
        self.viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"stepTwo"];
        [self presentViewController:self.viewController animated:NO completion:nil];
    }else {
    }
}

This viewController is a subclass of my BaseViewController - which I used for UI elements that is constant across all screens.

What I want to do is return the same instance of the viewController class when I change the segment control to a another view, using the same class.

Is this at all possible?

Not clear why you're using presentViewController:animated:completion: but it looks like you're doing things in the wrong way.

What you want to be doing is creating a container controller. So, the view controller which hosts the segmented control creates a number of view controller instances and adds them as child view controllers. Now, when the segments are selected you get the child at the selected index, remove the old view controllers view from its superview and add the new view controllers view as a subview.

You don't need to do it like that, but it will probably be cleanest. Your memory grows currently because you use instantiateViewControllerWithIdentifier: . All you really need to do is to keep an array of view controllers and reuse instead of recreating. That said, continually presenting view controllers is not wise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM