我想爲我的測驗應用程序創建一個得分。評分是我網頁上的一個標籤,我使用3個不同的頁面和評分標籤。一個是測驗,然後是正確的頁面和不正確的頁面。最初,我在測驗頁面上將標籤的值設置爲0。然後在選擇正確的答案後,它會進入相應的頁面並更新分數。因此,從0開始,它變爲1.然後它回到問題頁面,標籤當前爲1,並且當答案再次正確時,應該更新爲2。我的問題是,我的標籤似乎無法更新。得分開始爲0,然後加1,但在此之後,得分被固定爲1.這是我的代碼。我很確定,我使用的邏輯存在問題,所以我非常感謝所有的幫助。得分問答遊戲在objective-c
*問題頁
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;
}
然後這裏是我的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;
代碼,我已經試過檢查strDefaultScore的使用NSLog的兩個頁面的價值,都返回0,這就是爲什麼不管我得到多少正確的答案,分數是1。我該如何糾正?
我對Objective-C的使用知之甚少,而且我一直在網上尋找幫助,但找不到任何東西,所以我實在不知道該如何去解決這個問題。
更新: 我設法弄明白了。我將這些代碼移動到了按鈕的事件上,所以現在看起來像這樣。
-(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];
}
這對我有用,但我做了硬編碼,所以我不得不把這個每個按鈕事件。另外,由於我所做的是硬編碼的,所以我非常肯定有更好的方法來做到這一點。這段代碼在else
條件
你永遠不會實例化'update'。聲明變量與分配和初始化對象不同。你需要調用'[[CorrectPage alloc] init]'並將結果賦給'update'。與其他片段中的'quiz'變量相同。 –