Saving data is an obvious part of most of your applications. In games you probably need to save records – names, scores, times, settings like the music volume. In applications you should save enabled options. If your application is big it’s great if you occasionally save the whole state / progress and even user terminates the app it can be restored during next launch.
Here you will learn how to save data locally on your device / simulator. It’s not as difficult it appears to be. Of course you could use an SQLite database and write a controller to inser / update / delete records but it’s much more advanced. From this tutorial you will learn how to use NSUserDefaults to save whatever you need.
The syntax is simple. To save your data use this code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:5 forKey:@"myNumber"]; [defaults setBool:YES forKey:@"switchEnabled"]; [defaults setFloat:0.24 forKey:@"sliderValue"]; [defaults setObject:@"Chris" forKey:@"myName"]; [defaults synchronize];
As you see above I have saved 4 values. myNumber is an integer and =5. switchEnabled is a boolean with logic value YES / true. sliderValue is a float and =0.24 and myName is an object – it’s a NSString and it holds English equivalent of my name
.
Now, to get values from any key you can use only one line of code for example:
int anInteger = [[NSUserDefaults standardUserDefaults] integerForKey:@"myInteger"];
I prepared for you a project, where 3 different values are saved during any change, and loaded with the launch of the application. You can change there slider value, enter your name, and press the button – whenever the button is pressed the value below grows. You can quit and launch the application and see what happens.


How would I do this with a UIwebview loading a local resource index.html file?
Here is the code.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *pdfPath1 = [[NSBundle mainBundle] pathForResource:@”index”
ofType:@”html”];
NSURL *pdfURL = [NSURL fileURLWithPath:pdfPath1];
NSURLRequest *URLReq = [NSURLRequest requestWithURL:pdfURL];
[webView1 loadRequest:URLReq];
}
Hi, how i could make it with views?
Thank you.
How would i save a picker view?
I guess in the same way like NSString (object)
Thank you so much for making these tutorials and making them so easy to understand,
- Daniel
Thank you so much! I have been looking for how to do this and was thinking I would have to save my stuff to a plist. This is so much easier.