0

I create a quiz game. Here is a part of my code:

- (void) viewDidLoad
{
logos = [[NSMutableArray alloc] init];
[logos addObject:@"adidas"];
[logos addObject:@"nike"];
[logos addObject:@"puma"];

[self showLogo];
}

int currentQuestionIndex;

- (void) showLogo
{

currentQuestionIndex++;

NSString *question = [logos objectAtIndex:currentQuestionIndex];

[_questionImage setImage:[UIImage imageNamed:question]];

...

}

If user will choose the right answer, "showLogo" will be called again to go to next question. So, Level is completed.

Everything works great.

Please help me to save the information/levels. IF level is completed, when user Launch game he have to start with saved level.

This is what I tried already:

- (void) checkAnswer
{

///... if user answered right

[[NSUserDefaults standardUserDefaults] setInteger:currentQuestionIndex forKey:@"currentLevel"];

[self showLogo];
/// so, I tried to save "currentQuestionIndex" forKey currentLevel, and call "showLogo"
}

and here is modified "showLogo"

- (void) showLogo
{

int savedLevel = [[NSUserDefaults standardUserDefaults] integerForKey:@"currentLevel"];

currentQuestionIndex = savedLevel+1 ;

NSString *question = [logos objectAtIndex:currentQuestionIndex];

[_questionImage setImage:[UIImage imageNamed:question]];

...

}

but doesn't work.. using this method, I tried to save score, and it works also..

Help please. Thanks

Sebastian
  • 7,670
  • 5
  • 38
  • 50
Mary Torh
  • 31
  • 1
  • 4

2 Answers2

1

As stated in the documentation, you cannot save a primitive (int) into NSUserDefaults. You will have to turn your int into a NSNumber before you can save it, by doing something like this:

NSNumber *questionIndex = [[NSNumber alloc] numberWithInt:currentQuestionIndex];

Then, when you load it back, if you need an int again you can use intValue

Ares
  • 5,905
  • 3
  • 35
  • 51
  • I tried the code in my answer, and it works. – tolgamorf Mar 05 '13 at 03:08
  • I think the problem is in my lines. It works, but when I re-launch app, every time my level increases without to answer question. :) So, my NSUserDefaults saves the current level. When I re-launch app, my code will read NSUserDefaults++, and Automatically go to the next level, and also save the current level and again... – Mary Torh Mar 05 '13 at 03:18
0

After setting a key-value in NSUserDefaults, you have to save it using the synchronize method.

[[NSUserDefaults standardUserDefaults] setInteger:currentQuestionIndex forKey:@"currentLevel"];
[[NSUserDefaults standardUserDefaults] synchronize];
tolgamorf
  • 809
  • 6
  • 23