I am trying to create a scoring for my quiz app. The score is a label on my page and I use 3 different pages with a score label. One is the quiz then the correct page and the incorrect page. Initially, I set the value of the label to 0 on the quiz page. Then upon selection of the correct answer, it goes to the corresponding page and updates the score. So from 0 it becomes 1. Then it goes back to the question page with the label currently 1 and should update to 2 when the answer is correct again. My problem is, my label can’t seem to get updated. The score starts out as 0 then add 1 but after that, the score is stuck to 1. Here’s my code for it. I’m pretty sure, there’s a problem with the logic I’m using for it so I really appreciate all the help.
*Question Page
if(score.text == @"")
{
int i = 0;
strDefaultScore = [[NSString alloc] initWithFormat:@"%i", i];
score.text = strDefaultScore;
}
else
{
CorrectPage *update = [[CorrectPage alloc] init];
strDefaultScore = update.updateScore;
score.text = strDefaultScore;
}
Then here’s my code for the CorrectPage
QuestionPage *quiz = [[QuestionPage alloc]init];
int i = 1;
int j = [quiz.strDefaultScore intValue];
int sum = i + j;
updateScore = [[NSString alloc] initWithFormat:@"%i", sum];
currentScore.text = updateScore;
I’ve tried checking the value of strDefaultScore for both pages using NSLog and both return 0 which is why the score is 1 no matter how many correct answers I get. How do I correct this?
I have extremely little to none knowledge in using Objective-C and I’ve been searching the web for help with this but can’t find any so I honestly have no idea how to go about this.
Update:
I’ve managed to figure it out. I moved the code on the event(s) for the buttons so it looks something like this now.
-(IBAction)btn1 {
//Redirect to the next page
CorrectPage *correct = [[CorrectPage alloc]initWithNibName:@"CorrectPage" bundle[NSBundle mainBundle]];
[self.navigationController pushViewController: correct animated:YES];
//Update the value of score
int newScore = [score.text integerValue];
int sum = newScore + 1;
updatedScore = [[NSString alloc]initWithFormat:@"%i", sum];
score.text = updatedScore;
//Pass the value of new score on the next page
[correct.currentScore setText: score.Text];
}
That worked for me but what I did was hardcoded so I had to put this on every button event. Also, since what I did is hard coded, I’m pretty much sure that there a better way of doing it.
Look closely at this code in the
elsecondition:Your
updateobject is not initialized, so it cannot respond to any messages. This would be better:But you would need to set the
updateScorevalue somehow.Also,
QuestionPage *quiz;has the same problem.