Reputation: 1191
I'm new to Objective-C and XCode and I've encountered such a problem.
How do you properly save the value to NSUserDefaults
.
I have value in
[_textFields objectAtIndex:2]).text
And trying to do this
[[[NSUserDefaults standardUserDefaults] setValue:((UITextField *)[_textFields objectAtIndex:2]).text)) forKey:@"Phone"];
[[NSUserDefaults standardUserDefaults] synchronize];
How do you do it properly?
Upvotes: 0
Views: 1820
Reputation: 2097
Use method setObject:forKey:
instead of setValue:forKey:
In NSUserDefaults
class:
[[NSUserDefaults standardUserDefaults] setObject:"Your Object" forKey:@"Phone"];
Upvotes: 1
Reputation: 1800
You are working with strings values. You should use setObjectForKey (save) and objectForKey (read). Here's an example
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *yourText = [[_textFields objectAtIndex:2] text]; // Your text
// Save
[userDefaults setObject:yourText forKey:kKey];
[userDefaults synchronize];
// Read
NSString *result = (NSString *) [userDefaults objectForKey:kKey];
Upvotes: 1
Reputation: 4623
Use setObject:forKey:
instead of setValue:forKey:
[[[NSUserDefaults standardUserDefaults] setObject:((UITextField *)[_textFields objectAtIndex:2]).text)) forKey:@"Phone"];
Update: You code will work if you really have that text field in the array. Here is the step by step broken down code to make it more clear:
UITextField* textField = [_textFields objectAtIndex:2]; // get your text field
NSString* text = textField.text; // get the actual value we are going to store
[[[NSUserDefaults standardUserDefaults] setObject:text forKey:@"Phone"]; // store it
Upvotes: 2
Reputation:
You need to use the setObject:forKey:
if you want to store property list objects (dictionaries, arrays, strings and numbers) in NSUserDefaults
. See the docs.
Upvotes: 0