NSUserDefaults not being updated.


Hi all!

before I post the last chapter of my GameKit Leaderboards overview, I faced some troubles with NSUserDefaults and I’d like to share with you what I found.

After saving the defaults, if you read carefully the documentation the synchronization can take some time to actually take place. I was testing my app and I was not waiting enough time to close my app. This short period (around 2 seconds) was not enough time to let the system synchronize the settings you just saved to disk. If you need this synchronization to happen on the fly, you need to use the synchronize method manually. This is the code I use to load and save my fx and music volume:

#pragma mark -
#pragma mark Save game settings
- (void)loadSettings {
LOG(@"INFO - EAGLView: Loading settings.");
// If the key "userDefaultsSet" is not set then it means that // no settings have been
// defined yet, so set the defaults otherwise load the settings if (![settings boolForKey:@"userDefaultsSet"]) { [settings setBool:1 forKey:@"userDefaultsSet"]; [settings setFloat:0.5f forKey:@"musicVolume"]; [sharedSoundManager setMusicVolume:0.5f]; [settings setFloat:0.75f forKey:@"fxVolume"]; [sharedSoundManager setFxVolume:0.75f]; } else {
[sharedSoundManager setMusicVolume:[settings floatForKey:@"musicVolume"]];  [sharedSoundManager setFxVolume:[settings floatForKey:@"fxVolume"]]; }
// Now that the settings values have been updated from the settings file, post a notification  // which causes the sliders on the settings view to be updated with the new values. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateSettingsSliders"
object:self]; }
- (void)saveSettings {
// Save the current settings to the apps prefs file
[settings setBool:1 forKey:@"userDefaultsSet"];  [settings setFloat:sharedSoundManager.musicVolume forKey:@"musicVolume"]; [settings setFloat:sharedSoundManager.fxVolume forKey:@"fxVolume"]; [settings synchronize]; }
I hope it helps!

“Thanks for watching!”

Anuncios

Acerca de lapsusmental

Computer engineer working as a Banking Applications Developer in a multinacional firm. Actually, this blog is intended to cover my latest, and more exciting, hobby I'm spending my spare time on: iPhone Game Development. Everything I managed to learn on my own or visiting the many sites where more skilled and experienced people share they knowloedge has room in this site.
Esta entrada fue publicada en Tutorials y etiquetada , , , , , , . Guarda el enlace permanente.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s