NSUserDefaults doesn't save - iphone

i'm trying to save some informations in an iphone/ipad app.
The problem is that it works but if i close the app (with the home button on the simulator or closing with cmd+q) the informations become lost!
this is my code (and, if you see, i used "syncronize")
- (IBAction)choose1{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose1" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)choose2{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose2" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
else if (var == #"choose2"){
[self pushViewController:view2 animated:YES];
}
}
I don't understand why :(

When comparing strings, you should use the isEqualToString method, ie:
if ([var isEqualToString:#"choose1"]){
Otherwise you are comparing actual objects rather than their contents.

I am not entirely sure, but maybe it is saving your defaults and the error is located somewhere else. I am thinking about your "openView" method:
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
/** you are comparing to "choose1" here as well. **/
else if (var == #"choose1"){
[self pushViewController:view2 animated:YES];
}
Another possibilty might be that you never call your choose1() or choose2() methods?
This would explain why the value is never changed.
Despite from these 2 possibilites I think there is no error in the code you use to change the UserDefaults.
Hope this helps.
Regards,
Gjallar

ah, i'm sorry: i'm italian so i used the word "choose" with the italian translation "scelta".
Here i translated in english and i wrote "choose1" but in my code i used "choose2" (or "scelta2" :P)
for the other possibility (that i've never called the function choose1() or choose2() )... no, i've called, of course!

Related

Retrieval of NSArray from NSUserDefaults returns empty array

I am experiencing strange behaviour with NSUserDefaults. I am initially storing an array to the user defaults in my AppDelegate.m:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:#"weekdayIDs"];
if (weekdayIDs == nil) {
weekdayIDs = [NSArray arrayWithObjects:#"su", #"mo", #"tu", #"we", #"th", #"fr", #"sa", nil];
[defaults setObject:weekdayIDs forKey:#"weekdayIDs"];
}
[defaults synchronize];
Now in a different view controller ContentViewController.m, I want to retrieve the array:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:#"weekdayIDs"];
But I just get an array without objects, although its count == 7. I also used arrayForKey: but with the same result. I added a screenshot from my breakpoint.
I am regularly using NSUserDefaults, but currently I am bit stuck on this. It's probably a stupid mistake, anyone care to help?
Thank you so much!
-- Update:
I also figured it might be a problem with the init of the NSArray in the first place, but even replacing its objects with manually created NSString *dwid_su = [NSString stringWithString:#"su"]; didn't work.
Your code works perfectly.
Just, print the description of you array and you will see what you want.
Right click on weekdayIDs variable and select Print Description of weekdayIDs
or use through lldb debugger console po weekdayIDs
or NSLog(#"%#", weekdayIDs);
Here the results.

NSUserDefaults returns before it has been set

Im making an app that takes two strings and an int. I want these to be displayed on another view.
I have put them into an array and Im trying to store them in the NSUserDefaults. I have managed to get this data stored. The problem that im having is that when I change the data and save it again The function that gets the array is called before the one that sets it . So the application always displays the previous data.
I thought It would be easy to fix by changing when the functions are called.
but from the code it looks to me lie they are in the right order.
2012-09-26 13:55:02.764 BeerDivider[4377:907] array returnd = (
2,
"Person 1",
"Person 2"
)
2012-09-26 13:55:02.773 BeerDivider[4377:907] array saved = (
5,
"Person 1",
"Person 2"
)
I can see from logging the array that they are called in the wrong order.
Please can anyone see where im going wrong. This is my first objective-c/xcode post so not sure what code you want to see. I will put in all of it.
http://pastebin.com/BX5gqp17
Sorry if this is a lot of code.
Thanks for the help.
EDIT: update the code
EDIT2: I think what is happening is similar to this iOS do the button's action before prepareSegue
First Take a look on Apple documentation of NSUserDefault
NSUserDefault always return the data which you saved in it
Dont forgot to write [defaults synchronize];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourArray forKey:#"YourKey"]
[defaults synchronize];
According to your given code.
-(void)saveInfo:(NSArray *)myArray
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myArray forKey:#"array"];
[defaults synchronize];
NSLog (#"array saved = %#", [defaults objectForKey:#"array"]);
}
and now check result
Do this:
-(void)saveInfo:(NSArray *)myArray
{
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:#"array"];
[[NSUserDefaults standardUserDefaults] synchronize]; //u forgot this
NSLog (#"array saved = %#", myArray);
}

Saving and Retrieving UILabel value with NSUserDefaults

I trying to save UILabel value to NSUserDefaults. I did IBAction with this code:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:#"result"];
[prefs synchronize];
}
Then, I connect it to button with Touch Up Inside.
What log shows after I pressed the button:
result = 0;
When I pressed a second time, then it works.
result = "28.34";
What I'm doing wrong and how can I retrieve a result?
EDIT
With this code I display result in log. I put it to same action.
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
Your code looks correct, so the issue is probably not the function you posted but rather the code that contains your NSLog. You might be logging the value in a way that misses the first time it gets set.
Your log statement should be
NSLog(#"%#",[[NSUserDefaults
standardUserDefaults]
objectForKey:#"result"]);
This should be after you set the object in NSUserDefaults.
Add this to your applicationDidFinishLaunching in appDelegate or in init method in viewController(you have to create one) :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(prefs == nil)
{
[prefs setObject:#"anything" forKey:#"result"];
[prefs synchronize];
}

Storing preferences in NSUser Defaults to recall later

Been working on some code streamlining and have realised that it would be really helpful if my app had a preferences system.
Now here's how my code works.
A method runs based upon an integer stored in NSUserDefaults
e.g.
if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 040){
[self spaceDown];
}
else if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 10040){
[self ctrldown];
[self spaceDown];
}
Now what I want to do is when I exit the view (via a specific button) is to dump the value of #"scifi1" into a new preference, say for example - an integer named #"savedscifi1"
Now I know how to save integers into NSUserDefaults,
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:VALUEHERE forKey:#"savedscifi1"];
[userDefaults synchronize];
However - I'm not sure how I can substiture in the value of scifi1 instead of (in this case) 'VALUEHERE' - can anyone help with this? I feel it's really simple but I can't help but think I'm being a bit thick...sleep deprived and approaching a deadline! I know I can't just call up #"scifi1"but beyond that....??
NSInteger value = [[NSUserDefaults standardUserDefaults] integerForKey: ...];
[[NSUserDefaults standardUserDefaults] setInteger: value forKey: ...];

Can I change the apps view based on if a file has been saved?

Please help! I'm a newbie to programming and I'm having the following trouble. I am trying to write my first iphone app and I would like it to do the following.
When the app launches user enters name, presses button and goes to new view. Their name is saved to file and used through out the app. That much I have managed.
I would like the app to check to see if there is a saved file when it is launched and go directly to second view instead of the first view. I'm have search for days looking for an answer and I'm still not sure how to do this.
At the risk of seeming stupid do I use an IF statement and how do I write it. Please help.
Thanking you in advance.
You have to use NSUserDefaults for storing the user name and pass words. If you want to store more data's, have to use plist(Documents Directory) or core data or SQLite.
// Store the data
[[NSUserDefaults standardUserDefaults] setObject:#"yourPasswordString" forKey:#"YourKey"];
// Retrieve the data
NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:#"YourKey"];
Once you retrieved the data, you have to check the conditions like,
if(passWord == nil)
{
//load first view
}
else
{
// load second view
}
Thanks!
if you're using NSUserDefaults to save it then all you have to do is try reading the value into a string, then check if it is nil, if it is, then the files isn't there and you would load your first view, if it was, then load your second view.
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"yourKey"];
if(tempStr == nil)
{
//load your first view
}
else
{
// load your second view
}
You need to read your key back out in order to test if it is nil, the way you are doing this, you will never be nil and will always use the else choice, you need to set your object elsewhere, probably in the if statement.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if (tempStr == nil || [tempStr isEqualToString:""])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
ClubSearchViewController *CSearch = [[ClubSearchViewController alloc]initWithNibName:#"ClubSearchViewController" bundle:Nil];
[self presentModalViewController:CSearch animated:YES];
}
else
{
SearchMenu *SMenu = [[SearchMenu alloc]initWithNibName:#"SearchMenu" bundle:nil];
[self presentModalViewController:SMenu animated:YES];
}
}
-(IBAction)LogOutButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"" forKey:#"UserName"];
[prefs synchronize];
}