lunes, 19 de diciembre de 2011

How to use NSUserDefaults

NSUserDefaults is a useful class used to store data in the device, you can save and access information quickly.

  1. //First we get the singleton initialization for NSUserDefaults
  2. NSUserDefaults *myPreferences = [NSUserDefaults standardUserDefaults];
  3. // We are trying to save our volume value
  4. [myPreferences  setDouble:0.9 forKey:@"Volume"];
  5. //We will force to synchronize
  6. [myPreferences  synchronize];

Notice that in this case we have saved our volume value which is a double, but we can store integer, string, even an object to NSUserDefaults class.

So now we can call synchronize to synch all the values that we have been set. Synchronize method is not necessary because it is called during a period of time, but you can call it to ensure that your data is synched.

So now if we need to get the value of our volume, we can just write:

  1. //We use our NSUserDefaults object to get the Volume
  2. double volume = [myPreferences doubleForKey@"Volume"];

And that's all, we can store some values in our device using this simple class.

No hay comentarios:

Publicar un comentario