views:

52

answers:

4

Hi

In my game I want to save a set of integers as statistics players can view. E.g number of deaths. This is an int I simply increase by one each time they get a game over.

How can I save this then have it at that number when I relaunch the game?

Thanks.

EDIT:

Ok after reading a few answers Im thinking writing to a plist is the way forward. I have been looking at tutorials but lets say I try this:

scoreData *score = [scoreData sharedData];
[dictionary setValue:score.highScore forKey:@"key2"];
[dictionary writeToFile:@"stats.plist" atomically:NO];

I have accessed my singleton with my score inside. Now when trying to setValue I get an error saying Im trying to convert an int to object.

Im not sure how else to approach it. It seems simple enough, however everywhere I look seem to give essentially the same approach.

Thanks for the help thus far, anymore is appreciated.

A: 

You can write to a file (i.e. plain C functions fopen() etc), can use your own classes and use NS(Keyed)Archiver, or use NSUserDefaults to save data.

Eiko
Of those alternatives, NSUserDefaults seems most appropriate.
Graham Lee
+1  A: 

Any number of a lot of ways.

If you are only saving this and maybe a couple other simple things, using user defaults is probably the best idea.

If however, you are saving a lot more items than just a few, you may want to either use your own property list (if the number of items is less than 200 or so).

If you have a lot of settings, I generally advise folks to look at Core Data instead. It's fast with lots of items, whereas the other two, not so much.

jer
Property list file is also a nice idea. Core Data just for a couple of integers is very ambitious, though :)
Eiko
Yeah but I don't know if he's got other things going on under the hood, or what else he may want to save. Might as well put it on the table and let him decide which is appropriate for his case. :)
jer
A: 

Try...

[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:@"HighScore"];
highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];
Jordan
The first line of your code is just wrong. `-setValue:forKey:` doesn't exist. You instead want `-setInteger:forKey:`.
jer
@Jer Tried to do it from memory. Fixed. SO obj-c validator would be a nice addition. Thanks ;)
Jordan
+1  A: 

I would not abuse NSUserDefaults (Apple discouraged this at WWDC this year). Instead why not simply create an NSMutableDictionary and then store NSNumber objects in it. The MutableDictionary can easily be written to file and as is easily read in.

Felix