Accessing the value of a variable in the Root class from a subclass

与世无争的帅哥 提交于 2019-12-25 02:04:03

问题


I really can not figure this one out. I have a VC called additionalMathViewController which displays questions to the user. If the user answers incorrectly the user is directed to another VC which is a subclass of additionalMathViewController called incorrectViewController.

#import "ViewController.h"
@interface additionalmathViewController : ViewController{
int currentQuestion;
}

currentQuestion is a counter variable which increases everything the user gets a question right and another question can be displayed. if the user get the question wrong I want to go to incorrectViewController. Here is my code

- (IBAction)SelectA:(id)sender {
if ([self.correctAns isEqualToString:@"A"]) {
       [self showNextQuestion];
}
else{
  [self performSegueWithIdentifier: @"segueToIncorrect" sender:nil];
}
}

If the user selects A and it is correct show another question. If it is wrong perform Segue to incorrectViewController

#import "additionalmathViewController.h"
@interface IncorrectImageViewController : additionalmathViewController

Here I want to grab the value of currentQuestion from additionalMathViewController

incorrectImage.image = [UIImage imageNamed:left[currentQuestion]];

This current image is not the value from the additionalmathViewController

Any ideas?


回答1:


The new view controller is a new instance, therefore has no idea what the previous instance had for a value. You need to pass your currentQuestion value to the new controller in prepareForSegue method.

Make currentQuestion a property

@interface IncorrectImageViewController
  @property (copy) NSInteger currentQuestion;
..

And then in the prepareForSegue set the value on the destination controller.

@implementation additionalmathViewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    IncorrectImageViewController *incorrect = [segue destinationViewController];
    incorrect.currentQuestion = self.currentQuestion;
}


来源:https://stackoverflow.com/questions/15531352/accessing-the-value-of-a-variable-in-the-root-class-from-a-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!