ios cocoa-touch nsuserdefaults

ios - ¿Guardar cadena en el NSUserDefaults?



cocoa-touch (15)

¿Cómo guardar una cadena en el NSUserDefaults ?


Algo como esto:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // saving an NSString [prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

Luego para recuperar:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // getting an NSString NSString *myString = [prefs stringForKey:@"keyToLookupString"];

Realmente deberías revisar la Referencia de clase NSUserDefaults de Apple y quizás también este tutorial: Tutorial de programación de iPhone - Guardar / recuperar datos usando NSUserDefaults


Aquí es cómo hacer lo mismo con Swift;

var valueToSave = "someValue" NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")

Para recuperarlo más tarde;

if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") { // Do something with savedValue }

En Swift 3.0

var valueToSave = "someValue" UserDefaults.standard.set(valueToSave, forKey: "preferenceName") if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") { }


Aquí para Swift, creo dos funciones que requieren guardar y recuperar valor para la clave de Preference

Puede ser que esto sea una ayuda completa para ti.

// para guardar el objeto

static func setObject(value:AnyObject ,key:String) { let pref = NSUserDefaults.standardUserDefaults() pref.setObject(value, forKey: key) pref.synchronize() } static func getObject(key:String) -> AnyObject { let pref = NSUserDefaults.standardUserDefaults() return pref.objectForKey(key)! }


En Swift4.2 y Xcode 10

//Save UserDefaults.standard.set(true, forKey: "Key1") //Bool UserDefaults.standard.set(1, forKey: "Key2") //Integer UserDefaults.standard.set("This is my string", forKey: "Key3") //String UserDefaults.standard.synchronize() //Retrive UserDefaults.standard.bool(forKey: "Key1") UserDefaults.standard.integer(forKey: "Key2") UserDefaults.standard.string(forKey: "Key3") //Remove UserDefaults.standard.removeObject(forKey: "Key3")


No olvide esta afirmación porque de lo contrario no siempre funcionará:

[standardUserDefaults synchronize];


Una buena práctica es también usar una constante para la clave para evitar errores donde no almacena y lee con la misma clave

NSString* const TIME_STAMPS_KEY = @"TIME_STAMPS_KEY";


actualización para Swift 3

func setObject(value:AnyObject ,key:String) { let pref = UserDefaults.standard pref.set(value, forKey: key) pref.synchronize() } func getObject(key:String) -> AnyObject { let pref = UserDefaults.standard return pref.object(forKey: key)! as AnyObject }


más precisamente

-(void)saveToUserDefaults:(NSString*)myString { NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; if (standardUserDefaults) { [standardUserDefaults setObject:myString forKey:@"timestamps"]; [standardUserDefaults synchronize]; } }


[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]


En Swift 4.0.3 Xcode 9

============set Data in UserDefaults ========= UserDefaults.standard.set(userName, forKey: "userName") UserDefaults.standard.synchronize() ============Get Data in UserDefaults ========= let userName = UserDefaults.standard.string(forKey: "userName") print(userName ?? "Gera") userNameTextField.text = ""+userName!


Para ahorrar usa esto:

[[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"KTerminated"]; [[NSUserDefaults standardUserDefaults]synchronize];

Para el uso de Retriveing ​​esto:

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];


Primera vista

{ NSMutableArray *array; } - (void)viewDidLoad { [super viewDidLoad]; array = [[NSMutableArray alloc]init]; array = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; NSLog(@"%lu",(unsigned long)array.count); if (array>0) { for (int i=0; i<array.count; i++) { NSDictionary *dict1 = @{@"Username":[[array valueForKey:@"Username"] objectAtIndex:i],@"Mobilenumber":[[array valueForKey:@"Mobilenumber"] objectAtIndex:i],@"Firstname":[[array valueForKey:@"Firstname"] objectAtIndex:i],@"Lastname":[[array valueForKey:@"Lastname"] objectAtIndex:i],@"dob":[[array valueForKey:@"dob"] objectAtIndex:i],@"image":[[array valueForKey:@"image"] objectAtIndex:i]}; NSLog(@"%@",dict1); NSArray *array1 = [[NSArray alloc]initWithObjects:dict1, nil]; [[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"UserList"]; } } }

Selector de imágenes

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; self.imaGe.image = chosenImage; [picker dismissViewControllerAnimated:YES completion:NULL]; }

  • (IBAction) submitBton: (id) remitente {

    NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray: [[NSUserDefaults standardUserDefaults]objectForKey: @"userlist"]]; UIImage *ima = _imaGe.image; NSData *imagedata = UIImageJPEGRepresentation(ima,100); NSDictionary *dict = @{@"Username":_userTxt.text,@"Lastname":_lastTxt.text,@"Firstname":_firstTxt.text,@"Mobilenumber":_mobTxt.text,@"dob":_dobTxt.text,@"image":imagedata}; [array2 addObject:dict]; [[NSUserDefaults standardUserDefaults]setObject:array2 forKey:@"userlist"]; NSLog(@"%@",array2); [self performSegueWithIdentifier:@"second" sender:self]; }

    • (IBAction) selectImg: (id) remitente {

      UIImagePickerController * picker = [[UIImagePickerController
      alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType =
      UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController: selector animado: SÍ finalización: NULL];

      }

segunda vista {NSMutableArray * arr; }

- (void)viewDidLoad { [super viewDidLoad]; arr =[[NSMutableArray alloc]init]; arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; } #pragma mark- TableView DataSource -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return arr.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellId = @"tablecell"; TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId]; cell.userLbl.text =[[arr valueForKey:@"username"] objectAtIndex:indexPath.row]; cell.ageLbl.text =[[arr valueForKey:@"dob"] objectAtIndex:indexPath.row]; cell.profileImg.image =[UIImage imageNamed:[[arr valueForKey:@"image"] objectAtIndex:indexPath.row]]; return cell; }


-(void)saveToUserDefaults:(NSString*)string_to_store keys:(NSString *)key_for_the_String { NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; if (standardUserDefaults) { [standardUserDefaults setObject:string_to_store forKey:key_for_the_String]; [standardUserDefaults synchronize]; } }

Y llámalo por:

[self saveToUserDefaults:@"string_to_store" : @"key_for_the_string"];

Recupera la cadena usando:

NSString * stored_string = [[NSUserDefaults standardUserDefaults] stringforkey:key_for_the_String]


NSString *valueToSave = @"someValue"; [[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"]; [[NSUserDefaults standardUserDefaults] synchronize];

para recuperarlo mas tarde

NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"preferenceName"];


NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // saving an NSString [prefs setObject:@"TextToSave" forKey:@"keyToLookupString"]; // saving an NSInteger [prefs setInteger:42 forKey:@"integerKey"]; // saving a Double [prefs setDouble:3.1415 forKey:@"doubleKey"]; // saving a Float [prefs setFloat:1.2345678 forKey:@"floatKey"]; // This is suggested to synch prefs, but is not needed (I didn''t put it in my tut) [prefs synchronize];

Recuperando

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // getting an NSString NSString *myString = [prefs stringForKey:@"keyToLookupString"]; // getting an NSInteger NSInteger myInt = [prefs integerForKey:@"integerKey"]; // getting an Float float myFloat = [prefs floatForKey:@"floatKey"];