问题
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