How to Read String from NSUserDefaults - objective-c

I have an object at the root of plist that stores objects and keys (one of which is input from a user textfield). I have no problem writing and creating structure; it's trying to read values that causing problem. Below code I used to write the data, can someone tell me how to read the string [val] and [myKey]?
thank you!
#define defaultValue #"Your Name"
#define myKey #"PersonName"
- (void)textFieldAction:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *val;
// Get the new value from the textfield
val = [myTextField stringValue];
if ([val isEqualToString:defaultValue]) {
[defaults removeObjectForKey:myKey];
} else {
// [defaults setObject:val forKey:myKey];
NSDictionary *my_dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"Name", #"PersonName",
#"Email", #"PersonEmail",
#"Dept", #"PersonDept",
#"Job", #"PersonJob",
val, myKey,
#"Status", #"PersonStatus",
nil];
[defaults setObject: my_dict forKey: #"Person"];
[[NSUserDefaults standardUserDefaults] registerDefaults:my_dict];
I would like to automatically populate the textfield with the [val], for [myKey], if the user has the info already in the plist. Here's the code I'm trying to use for that:
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] objectForKey:myKey];
NSString *val = [defaults stringForKey:myKey];
if (val == nil) val = defaultValue;
[myTextField setStringValue:val];

You can write the value into NSUserDefault like the following:
[[NSUserDefaults standardUserDefaults] setValue:[myTextField stringValue] forKey:#"Person"];
And read it later like the following:
[myTextField setStringValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"Person"];
So you can simplify your code into:
- (void)textFieldAction:(id)sender {
[[NSUserDefaults standardUserDefaults] setValue:[myTextField stringValue] forKey:#"Person"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
You can set a default value with the registerDefaults:. And when you can retrieve that value simply by calling:
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
// ...
[[NSUserDefaults standardUserDefaults] registerDefaults:#{#"Person", defaultValue}]
NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:#"Person"];
[myTextField setStringValue:value];
// ...
}

If I understand correctly, you should be able to do what you need by simply doing:
NSString * val = [[NSUserDefaults standardUserDefaults] objectForKey: myKey];
[textfield setText: val];
NSUserDefaults Reference Page

myTextField.text = [[NSUSerDefaults standardUserDefaults] objectForKey:myKey];

Related

How to save fields correctly with NSUserDefaults?

I'm creating a program that saves a String from one text field and an integer from a second text field. I am trying to use NSUserDefaults, but I can't seem to get either of them to save correctly when I run the program. It crashes when I press the save button with the breakpoint while handling the NSUserDefaults. Am I doing something wrong? I skimmed through the documentation, but it didn't help. Can I even use 2 different instances of NSUserDefaults?
- (IBAction)save:(id)sender {
//Save stuff fropm textfields
NSString* name = _nameText.text;
int count = [_countText.text intValue];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"name"];
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:#"count"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (IBAction)load:(id)sender {
//Load stuff from NSUserDefaults
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* loadstring = [defaults objectForKey:#"name"];
_nameText.text = loadstring;
NSUserDefaults* defaults2 = [NSUserDefaults standardUserDefaults];
NSInteger loadint = [defaults2 integerForKey:#"count"];
_countText.text = [NSString stringWithFormat:#"%li", (long)loadint];
}
Declare defaults = [NSUserDefaults standardDefaults]; in your viewDidLoad (and NSUserDefaults* defaults; in .h) and use this code:
- (IBAction)save:(id)sender {
//Save stuff fropm textfields
NSString* name = _nameText.text;
int count = [_countText.text intValue];
[defaults setObject:name forKey:#"name"];
[defaults setInteger:count forKey:#"count"];
[defaults synchronize];
}
- (IBAction)load:(id)sender {
//Load stuff from NSUserDefaults
_nameText.text = [defaults stringForKey:#"name"];
_countText.text = [NSString stringWithFormat:#"%li", (long)[defaults integerForKey:#"count"]];
}

Only first object of NSMutableArray is stored in NSUserDefaults

I am trying to store a queue of UILocalNotification to solve the limit problem. I used this approach and it does archive and unarchive my object but only the first one.
How do I archive all objects from my NSMutableArray?
Code
// init/unarchive queue
if (self.queue == nil)
{
// try loading stored array
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:#"LocalNotificationQueue"];
if (dataRepresentingSavedArray != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil) {
self.queue = [[NSMutableArray alloc] initWithArray:oldSavedArray];
}
else
{
self.queue = [[NSMutableArray alloc] init];
}
}
else
{
self.queue = [[NSMutableArray alloc] init];
}
}
// add
[self.queue addObject:notif];
// store queue
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self.queue] forKey:#"LocalNotificationQueue"];
If I add items 1,2,3. Restart and load. I have only 3.
Add 1,2,3. Restart and load. I have 3, 1, 2.
If it matters. This is a Phonegap/Cordova CDVPlugin.
After
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self.queue] forKey:#"LocalNotificationQueue"];
You need to call
[[NSUserDefaults standardUserDefaults] synchronize]
To save the user defaults.
Try this, without the NSKeyedArchiver:
[[NSUserDefaults standardUserDefaults] setObject: self.queue] forKey:#"LocalNotificationQueue"];

NSUserDefaults write string and clean it after

I write a string in NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject: myString forKey: # "String"];
Then I take out this string from NSUserDefaults and return
- (NSString *) retrieveString
{
     NSString * recoveredString = [[NSUserDefaults standardUserDefaults] objectForKey: # "String"];
     return recoveredString;
}
Then in viewDidLoad write the returned string in another string
NSString * filePath = [self retrieveString];
I need to delete a string of NSUserDefaults after I was returning to her in - (NSString *) retrievestring
I do so
- (NSString *) retrieveString
{
     NSString * recoveredString = [[NSUserDefaults standardUserDefaults] objectForKey: # "String"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey: # "String"];
     return recoveredString;
}
But this does not work, the line is not deleted.
How to fix it
Thanks to all.
NSUserDefaults updates its data periodically only, not each and every time a setter or getter is called. If you want an immediate update, call
[[NSUserDefaults standardUserDefaults] synchronize];
You need to add the synchronize call AND move your return call (so it is the last line in the method). So, your code should like this:
- (NSString *) retrieveString
{
NSString * recoveredString = [NSString stringWithString:[[NSUserDefaults standardUserDefaults] objectForKey: # "String"]];
[[NSUserDefaults standardUserDefaults] removeObjectForKey: # "String"];
[[NSUserDefaults standardUserDefaults] synchronize];
return recoveredString;
}

Setting value in nsuserdefaults

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?
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
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];
Use method setObject:forKey: instead of setValue:forKey:
In NSUserDefaults class:
[[NSUserDefaults standardUserDefaults] setObject:"Your Object" forKey:#"Phone"];
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.

iPhone:Store & Retrieve NSMutableArray object

appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, #"name",image ,#"image", nil];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(#"Category Data:--->%#",appDelegate.categories);
I am successfully added object mutabledictionary into mutuablearray but I want to store that array and retrieve when application is launched so please give me idea to develop this functionality.
Thanks in advance.
//you can save array in NSUserDefaults like below
if ([[NSUserDefaults standardUserDefaults] valueForKey:#"detail"]==nil)
{
NSMutableDictionary *dic_detail = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, #"name",image ,#"image", nil];
NSMutableArray *ary_detail = [[NSMutableArray alloc] init];
[ary_detail addObject:dic_detail];
[[NSUserDefaults standardUserDefaults] setObject:ary_detail forKey:#"detail"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//if you want read that array you can read like below in your app
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"detail"]];
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(#"applicationDidEnterBackground = %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"detail"]);
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(#"applicationWillEnterForeground = %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"detail"]);
}
in my log its printing like this
applicationDidEnterBackground = (
{
image = img1;
name = cat1;
}
applicationWillEnterForeground = (
{
image = img1;
name = cat1;
}
Perhaps something like this:
NSMutableArray * array = [NSMutableArray array];
appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, #"name",
image ,#"image",
array, #"array", nil];
Something like:
On Application launch:
[[NSUserDefaults standardUserDefaults] registerDefaults:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSArray new], #"StoredArray", nil]];
In your class that "owns" control of the array:
- (void)setArray:(NSMutableArray *)array {
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"StoredArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSArray*)array {
return [[[NSUserDefaults standardUserDefaults] arrayForKey:#"StoredArray"] mutableCopy];
}
Hope this helps!