views:

95

answers:

2

I have a int which is my high score:

NSInteger highScore;

I want to store it persistently to disk

Do I have to convert it to a string, then write the string to a file, then parse it back when I want to read it. Or is there a better way to store small amounts of data?

A: 

You can write the NSInteger to a file withougt converting it to a string like so:

NSInteger foo = 134;
fwrite(&foo, sizeof(NSInteger),1, filePointer);

Then you can just read it back again using fread the same way.

Roe
Philippe Leybaert
Ah yes, fixed >.<
Roe
Emil
We want a pointer to the NSInteger.
Roe
+3  A: 

Try saving the integer in NSUserDefaults.

There is an example of someone storing an integer in there here.

Douglas
Why was this downvoted? Sounds right to me...
Georg Fritzsche
great! I thought there would be a simple answer in the iphone sdk
Robert
@Robert: Simpler than `[[NSUserDefaults standardUserDefaults] setObject:highScore forKey:@"highScore"]`? I find that unlikely.This is what NSUserDefaults was meant for. It's a one-liner. Doesn't get any simpler.
Dan Ray
@Dan Ray: he means that this solution (NSUserDefaults) is simpler than writing to disk by hand. As in, when he wrote the question, he "thought there would be a simpler answer in the iphone sdk" than converting to string, writing to file, then parsing string.
Douglas