Guardando los ajustes con la clase NSUserDefaults
- (IBAction)selectionChanged:(id)sender {
NSInteger index = ((UISegmentedControl*)sender).selectedSegmentIndex;
// Get the shared defaults object.
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
// Save the index.
[settings setInteger:index forKey:@"MySelectedValueKey"];
// Write them to disk - this is optional here,
// but should be done when the app exits.
[settings synchronize];
}
Como puedes ver es bastante sencillo guardar cosas. Primero capturo el index seleccionado del UISegmentedControl, y después lo guardo con su correspondiente "key" en "MySelectedValueKey". El key puede ser cualquier cosa que quieras probablemente podría establecerse con un #define. Lo último que hacemos es sincronizar con la base de datos, la cual guarda todos los cambios en el disco. Esto no tiene que hacerse aquí, pero al menos deberías hacerlo cuando la aplicación se termina o arriesgarás que no se guarden tus cambios.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
// Get the settings and set the selected index.
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
if([settings objectForKey:@"MySelectedValueKey"] != nil) {
options.selectedSegmentIndex = [settings integerForKey:@"MySelectedValueKey"];
}
return YES;
}
NSUserDefaults no tiene una gran manera de saber si un key existe. Como objectForKey devolverá nil si no hay nada allí, me gusta usar este método. Si algo está allí, entonces usamos algo más específico como integerForKey y establecemos el índice seleccionado al valor guardado en la base de datos. NSUserDefaults doesn't have a great way to see if a key exists. Since objectForKey will return nil if there's nothing there, I like using that method. If something is there, then I use the more specific integerForKey method and set the selected index to the value stored in the database.