Saving a single int in NSdefaults

I was looking for tutorials on how to store certain things in NSuserdefaults, but only found material that deals mainly with arrays and strings. Can someone bring me or give some knowledge about saving and loading int. For my application, I have int highScore = 0; but I want it to save this int in your NSuserdefaults, so when my game loads, it shows your current high score that you recently reached.

+4
source share
3 answers
int highScore = 0; // write [[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:@"someKey"]; // read highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"someKey"]; 
+12
source

Save it as NSNumber using -[NSNumber numberWithInt:highScore] .

+2
source

NSUserDefaults can only process property list objects. Property list objects must be one of the following types: NSArray , NSDictionary , NSString , NSData strong>, NSData, and NSNumber .

NSUserDefaults has a number of helper methods that automatically convert numeric types to NSNumber objects. setInteger: forKey: and integerForKey: and helper methods for integers. These methods expect integers to be of type NSInteger . NSInteger is not an object. This is just a typedef for long int . Your code defines highScore as int . This may be causing the problem.

I prefer to convert c numeric types to NSNumber objects and store the object. Although this seems like extra work, it can simplify your code as everything returned by NSUerDefaults will be an object and can be handled in a uniform way.

0
source

All Articles