Posts Tagged ‘data’

Saving data

April 26th, 2009

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"];
Since now anInteger=5.
If you try to load a value that doesn’t exist you will get 0 for integers, doubles, floats, NO for booleans and nil for objects.

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.

savesimulator

xcodeproj

Download the project