Saving and Retrieving UILabel value with NSUserDefaults - iphone

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];
}

Related

NSUserDefaults, saving data issue

So I have an app that lets you put in a title and an author on the front page, then you hit enter and it will go into the actual features of the app. I want to save the data with NSUserDefaults, so that when they click the enter button, it saves it *AND goes into the next view. I have it setup with the storybord already to go into the next view, but when I use this code:
-(IBAction)enter:(id)sender {
titleString = [[NSString alloc] initWithFormat:[title text]];
[title setText:titleString];
NSUserDefaults *titleDefault = [NSUserDefaults standardUserDefaults];
[titleDefault setObject:titleString forKey:#"stringkey"];
authorString = [[NSString alloc] initWithFormat:[author text]];
[title setText:authorString];
NSUserDefaults *authorDefault = [NSUserDefaults standardUserDefaults];
[authorDefault setObject:authorString forKey:#"stringkey2"];
}
It will always crash when you hit the button. I have all the NSStrings defined and such, so I don't see what the problem is. I also have it loading with:
title.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"stringkey"];
author.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"stringkey2"];
Under the viewdidload, so can I have some help as to why this wouldn't work?
Just to optimize your -enter:method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:title.text forKey:#"stringkey"];
[defaults setObject:author.text forKey:#"stringkey2"];
[defaults synchronize]; // this will store them instantly!
For the crash: can you please provide us with the exact crash log? Maybe your Button is linked to an unknown selector...
First, there are a few questions about this: here, here. Try searching around first, and at least let people know why the duplicate questions you found didn't work for you.
Secondly, I think you might benefit from adding a synchronize. Use this:
titleString = [[NSString alloc] initWithFormat:[title text]];
[title setText:titleString];
NSUserDefaults *titleDefault = [NSUserDefaults standardUserDefaults];
[titleDefault setObject:titleString forKey:#"stringkey"];
[titleDefault synchronize];
authorString = [[NSString alloc] initWithFormat:[author text]];
[author setText:authorString];
NSUserDefaults *authorDefault = [NSUserDefaults standardUserDefaults];
[authorDefault setObject:authorString forKey:#"stringkey2"];
[authorDefault synchronize];
I also changed the [title setText:authorString]; line to [author setText:authorString];. I do, however, think it is a bit redundant the way you are allocating the NSStrings to the value of the text fields and then setting the text back to the value of the string you created. I don't get the need. Anyway, hope this helps.

How to keep my data in a array-iphone sdk

I'm trying to create an application, and in that I'm receiving some contents from net and loading into and array, if I quit and run the app again i'm losing the data. How can I store the data in the app itself. Should I use some kind of database? If so which one and how can I implement that? I need to store only some string variables.
EDIT:
My app is tabbar based app, and have two tabs. Loading the arrays in one tab and loading that array in a table in the other VC. once I load the array and move to the second tab, the table is loaded with the array. If i go back and add few more values and then if i check, the added datas is not displayed in the table. And also, when I quit the app the table lose all the values, I need to keep the values in the table, even after i quit the app. How can I do that?
here is my code:
in viewdidload:
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:#"isItWorking"];
[simplePlistDb setObject:alertList forKey:#"myArray"];
[simplePlistDb synchronize];
in cellforrowatindexpath:-
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:#"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:#"myArray"];
for (NSString *str in myArray){
NSLog(#"Str:%#", str);
[loadArray addObject:str];
}
cell.textLabel.text = [loadArray objectAtIndex:indexPath.row];
}
Thank you.
You will want to look into Core Data if you want to save a decent amount of data to the iPhone. However, if not, you can just load the items in the array into a plist and load them from there at launch.
Plist Writing: How to create a new custom property list in iPhone Applications
CoreData: http://www.raywenderlich.com/934/core-data-tutorial-getting-started
Edit--->
As Nekto said, you can also use NSUserDefaults, but I advise mainly using NSUserDefaults for simple NSStrings and integers.
I think for your purposes NSUserDefaults will be enough : NSUserDefaults Class Reference.
Examples:
// save
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:#"isItWorking"];
[simplePlistDb setObject:[NSArray arrayWithObjects:#"very", #"cool", nil]];
[simplePlistDb synchronize];
// restore
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:#"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:#"myArray"];
for (NSString *str in myArray)
NSLog(#"%#", str);
}
You can use NSUserDefaults in order to store your data till the time your app is installed in your device.
How to write in NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"yourObject1" forKey:#"correspopndingKey1"];
[defaults setObject:#"yourObject2" forKey:#"correspopndingKey2"];
[defaults synchronize];
How to read from NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *temp1 = [defaults objectForKey:#"correspopndingKey1"];
NSString *temp2 = [defaults objectForKey:#"correspopndingKey2"];
You can store NSArray in a similar way.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:objArray forKey:#"correspopndingKey"];
[defaults synchronize];

problem in saving a value in iphone

when i enter a value in the iphone simulator and press the save button it only keeps the value until the simulator is running. and when i restart the simulator and press the load button it shows an earlier value entered by me.i.e, it is not able to keep the new value and keeps only old value.
i am using following loops for saving a file and loading a file.
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
[king setObject:noc.text forKey:#"save"];
}
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = [NSString stringWithFormat:tempstring];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
NSString *tempstring1 =[king stringForKey:#"save"];
noc.text = [NSString stringWithFormat:tempstring1];
}
// Your code
NSUserDefaults *king= [NSUserDefaults standardUserDefaults];
[king setObject:bookmarks forKey:#"Bookmarks"];
// saving it all
[king synchronize];
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
[sinner setObject:noc.text forKey:#"save"];
[sinner synchronize];
}
This should save the contents. You dont need two separate userdefaults. To load them you can try
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = tempstring;
NSString *tempstring1 =[sinner stringForKey:#"save"];
noc.text = tempstring1;
}
Hope this helps

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];
}

Cannot set NSUserDefaults field

I have the following code in my initialization (first time) of my app:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=#"1";
[defaults setObject:uid forKey:#"init_val"];
[defaults synchronize];
Much later in the code (in response to a button press) I check the value using:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *initVal=[defaults objectForKey:#"init_val"];
initVal is always nil. I have checked and init_val is set up exactly the same in my settings bundle as another field that I can set and read from without issue (they are both set up with a single field named "Key".
#mlewis54:
You can try this code. I am very sure that it will work for you.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=#"1";
[defaults setObject:uid forKey:#"init_val"];
[defaults synchronize];
For Retrieving Data You Should Use The Following Code :
NSString *initVal=[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"];
OR
NSString *initVal=[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"];
EDIT:
If still it gives nil, then you can use the following code:
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"]];
OR
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"]];
Hope this helps you.
Decelare this at an event on click of button ...
NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
[savedData setObject:userEmailTextField.text forKey:#"userid"];
and on load load the data and check the value you have entered is showing or not...
userEmailTextField.text =[[NSUserDefaults standardUserDefaults]objectForKey:#"userid"];
You need to use the line
NSString *initVal = [defaults stringForKey:#"init_val"];
- since it's a String you must use stringForKey. You can similarly use boolForKey to get a boolean value.
There's nothing wrong in your code, i tried to copy it in my project and it worked good,
so your error could be probably when you check initVal...
what's the code you use to see if initVal is nil?
and are you sure that when/where you check initVal, that var/oblect is still visible ?
try to insert this immediately after your reading code:
NSLog(#"____text read in pref: %#", initVal);
it writes this in my console window -> __text read in pref: 1
of course it's an NSString, i hope you keep it in mind it's not an int or a NSNumber when you check it...
luca
It might be that the initialisation isn't happening. Put an NSLog in there to check it's executed.
It works fine for me with the same code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=#"1";
[defaults setObject:uid forKey:#"init_val"];
[defaults synchronize];
NSUserDefaults *defaultss = [NSUserDefaults standardUserDefaults];
NSString *initVal=[defaultss objectForKey:#"init_val"];
NSLog(#"Value of initVal: %#",initVal);
O/P on console: Value of initVal: 1
So try to do it with the same code with print on console.
Are you sure you properly initialize NSUserDefaults? When I initialize, in my app delegate, I always create the default user defaults by creating a dictionary of the default values then:
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
Where appDefaults is the dictionary. Then you should be able to access them correctly.