Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults standardUserDefaults setInteger for a long long int

I'm trying to create a high score system in my iPhone app that allows me to store a long long int in the High Score save file, because I am expecting the high score values to be greater that a normal integer. But all I could find in terms of code was this:

   if (ScoreNumber > HighScore) {
    HighScore = ScoreNumber;
    [[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScoreSaved"];
}

The HighScoreSaved won't save correctly, once the Score Number achieves a value greater than 2,147,483,647 or the maximum integer value for a 4 byte integer, the HighScoreSaved will save a completely different integer value. Here is what I have in my ViewController.h in terms of data types:

    int y, RandomPosition;
    long long int ScoreNumber, HighScore;
    BOOL Start;

Just to reiterate and make sure I'm as clear as possible, I'm looking for a way to store a long long int high score value in objective-c. Any input would be much appreciated and this question may seem foolish but this is my first app using xcode and objective-c, so anything would be good. Thanks.

like image 455
gmoney242 Avatar asked Oct 27 '25 09:10

gmoney242


1 Answers

Rather than splitting the score into two parts yourself, store its value wrapped in NSNumber, like this:

[[NSUserDefaults standardUserDefaults]
    setObject:[NSNumber numberWithLongLong:HighScore]
    forKey:@"HighScoreSaved"
];

Retrieve the high score as follows:

HighScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScoreSaved"] longLongValue];
like image 76
Sergey Kalinichenko Avatar answered Oct 28 '25 22:10

Sergey Kalinichenko