Bagaimana cara menyimpan string ke dalam NSUserDefaults
?
Bagaimana cara menyimpan string ke dalam NSUserDefaults
?
Jawaban:
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];
untuk mendapatkannya kembali nanti
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"preferenceName"];
NSString *valueToSave = @"someValue";[[NSUserDefaults standardUserDefaults]setObject:valueToSave forKey:@"preferenceName"]; [[NSUserDefaults standardUserDefaults]synchronize
lebih tepatnya
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:@"timestamps"];
[standardUserDefaults synchronize];
}
}
standardUserDefaults
objek. Tidak apa-apa mengirim pesan ke nol di Objective-C.
synchronize
metode ini: "gunakan metode ini hanya jika Anda tidak dapat menunggu sinkronisasi otomatis (misalnya, jika aplikasi Anda akan keluar)" - NSUserDefaults Class Reference
synchronize
. Doc mengatakan: YA jika data berhasil disimpan ke disk, jika tidak NO.
Inilah cara melakukan hal yang sama dengan Swift;
var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")
Untuk mendapatkannya kembali nanti;
if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
// Do something with savedValue
}
Di Swift 3.0
var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")
if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {
}
Sesuatu seperti ini:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
Kemudian untuk mengambil:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
Anda harus benar-benar memeriksa Referensi Kelas NSUserDefaults Apple dan mungkin juga tutorial ini: Tutorial Pemrograman iPhone - Menyimpan / Mengambil Data Menggunakan NSUserDefaults
Jangan lupa pernyataan ini karena jika tidak, pernyataan ini mungkin tidak selalu berfungsi:
[standardUserDefaults synchronize];
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];
Mengambil
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"];
[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]
-(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];
}
}
Dan menyebutnya dengan:
[self saveToUserDefaults:@"string_to_store" : @"key_for_the_string"];
Ambil kembali string dengan menggunakan:
NSString * stored_string = [[NSUserDefaults standardUserDefaults] stringforkey:key_for_the_String]
FirstView
{
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"];
}
}
}
ImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imaGe.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
(IBAction) submitBton: (id) pengirim {
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) pengirim {
UIImagePickerController * picker = [[
alokasi UIImagePickerController ] init]; picker.delegate = diri; picker.allowsEditing = YA; picker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController: animasi pemilih: penyelesaian YES: NULL];
}
Tampilan kedua {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; }
Di Swift5 dan Xcode 10.2
//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")
Catatan: Simpan data teks (berarti String, Array, Kamus dll.) Di UserDefaults. Jangan menyimpan gambar di UserDefaults, itu tidak dianjurkan (Simpan gambar di direktori lokal).
Di sini Untuk Swift saya membuat dua fungsi yang memanggil untuk menyimpan dan mengambil kembali nilai untuk kunci dari Preferensi
Mungkin ini bantuan penuh untuk Anda
// untuk menyimpan objek
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)!
}
Di 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!