1

I was coding, and ran across this..

I don't understand why this is happening and I need help, can someone please help? :)

- (void)viewDidLoad
{
Start = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
Bottom1.hidden = YES;
Bottom2.hidden = YES;
Bottom3.hidden = YES;
Bottom4.hidden = YES;
Bottom5.hidden = YES;
Bottom6.hidden = YES;
Bottom7.hidden = YES;
Top1.hidden = YES;
Top2.hidden = YES;
Top3.hidden = YES;
Top4.hidden = YES;
Top5.hidden = YES;
Top6.hidden = YES;
Top7.hidden = YES;

Heli.center = CGPointMake(48, 145);

HighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"]; < issue HERE

Intro3.text = [NSString stringWithFormat:@"High Score: %i", HighScore];
0

3 Answers 3

5

integerForKey returns an NSUInteger value (aka unsigned long). I assume your HighScore variable is an int, which has less bytes than a long. Try casting to int:

HighScore = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];
0

I'm guessing it's in your second to last line. integerForKey: returns a NSUInteger (unsigned long), and HighScore is probably declared as an int (you don't show the declaration in your code). Either explicitly cast it using (int), or store it as an int in the user defaults (intForKey:). Good luck!

0

It would have been nice if you had included the declaration for HighScore, but I will assume it is an int because this is the type you are having trouble with. When you are assigning HighScore to the result of -[NSUserDefaults integerForKey:] you are assigning a variable of type NSUInteger to type int. This is the root of your problem. Because NSUInteger is typedef'd to unsigned long and long is a larger representation of a number than int, during assignment, you are losing precision. I have two recomendations.

@property (nonatomic) NSUInteger HighScore; // declare HighScore as NSUInteger

/* or */

HighScore = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];

The first simply declares HighScore as a NSUInteger to avoid the problem in the first place, the second casts the return type of the method to fit its assignment.

1
  • 1
    n.b. declaring it as NSUInteger is a good idea, but then be sure to change the string format specifier in stringWithFormat as %i won't do anymore. (I think it's %ul ? I recall with 64-bit support in XCode 5.1 I had to change to some odd specifier and cast NSUInteger to make these portable)
    – RobP
    Apr 9, 2014 at 4:58

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.