NSUserDefault NSString not getting displayed in label - iphone

I have a NSString that I use NSUserDefaults to store and move between multiple view controllers. The problem is, the NSString will not display in the label I am trying to show it in. Here is my code, I have no errors.
First View Controller:
NSString *scoreString = [NSString stringWithFormat:#"%d", score];
NSString *score = #"message";
[[NSUserDefaults standardUserDefaults]
setObject:scoreString forKey:#"score"];
Second view Controller:
- (void)viewDidLoad {
[[NSUserDefaults standardUserDefaults] objectForKey:#"Score"];
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"score"];
savedValue = score.text;
[super viewDidLoad];
}
I have no idea why the string is not getting displayed, the connections are all made. Any help would be great. Thanks!

savedValue = score.text;
Your assignment is backwards. You're (uselessly) overwriting the variable holding the string you fetched from NSUserDefaults with the current value of the text field.

I think what you want is
score.text = savedValue;
The following line is also not really doing anything:
[[NSUserDefaults standardUserDefaults] objectForKey:#"Score"];

I'm assuming in the second view controller, score is the name of your label?
If so, you should say
score.text = savedValue;

Related

UILabel text doesn't update after receiving notification

When I set a label using this
self.versionLbl.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"];
in the viewDidLoad method, it works when the view gets loaded but I also want to set the label when a notification was received.
- (void)receiveNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:#"versionNotification"]){
NSLog (#"Successfully received the notification!");
self.versionLbl.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"];
}
}
The string "Successfully received the notification!" gets printed out, but the label doesn't get updated/set with the string unless I reload the view again and the viewDidLoad method gets called.
EDIT
I found out that it has nothing to do with the notification, when I put self.versionLbl.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"]; in another function is doesn't get set aswell... it only gets set when I put it in the viewDidLoad method
Make sure that your label is not nil and that you're calling UIKit methods in the main thread. You can try this:
dispatch_async(dispatch_get_main_queue(), ^{
self.versionLbl.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"];
});
First of all make sure that the object stored in [[NSUserDefaults standardUserDefaults] objectForKey:#"version"]; is actually a NSString object.
If not you have several alternatives:
self.versionLbl.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"version"];
or
id versionObject = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"];
self.versionLbl.text = [NSString stringWithFormat:#"%#", versionObject];
or
id versionObject = [[NSUserDefaults standardUserDefaults] objectForKey:#"version"];
self.versionLbl.text = [versionObject stringValue];
Check IBOutlet at your UILabel. You should connect IBOutlet UILabel declared with a Property with label on your .xib file.
If its loading after the view has already loaded, try [myLabel setNeedsDisplay];

NSUserDefaults - storing and retrieving data

I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.
I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.
here's the code that Im displaying the NSUserDefaults stored info on a UILabel:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
if someone could point me in the right direction that would be great,
thanks
Put this text in
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
}
And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults
When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:
[[NSUserDefaults standardUserDefaults] synchronize];
This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.
Do not forget the use synchronize when you set some value
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:#"KEY_NAME"];
[defaults synchronize];
Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue = [defaults objectForKey:#"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : #"No Value";
Hope it helps
In Swift we can do it following way:
To save value:
let defaults = UserDefaults.standard
defaults.set(YOUR_VALUE, forKey: "YOUR_KEY_NAME")
To get value:
let defaults = UserDefaults.standard
let data = defaults.objectForKey("YOUR_KEY_NAME")
For more details visit:
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults

Use NSUserDefaults to access a stored object

I want to access text saved through NSUserDefaults and display it in a label that has already been defined called "name". My code is below, but it doesn't work. What should I do? Thanks for your help!
name = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
should be:
name.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
First, you should register your defaults someway like this: (this is only necessary if you want to add multiple items!)
NSDictionary *defaultsDict =
[NSDictionary dictionaryWithObjectsAndKeys:#"MyName", #"defaultName", #"MyAge", #"defaultAge", nil];`
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
Now use this assuming you have a label pointer:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[label setText:[defaults stringForKey:#"defaultName"]];

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

how to check nsuserdefaults is empty or not

i am getting a list of items from sqlite database and place them in an array.
i need to get this array first time my app runs.
for this i am saving this array into NSuserdafaults.
my code is like this
if ([[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"]) {
[[NSUserDefaults standardUserDefaults] setObject:appdelegate.categoriesList forKey:#"categories"];
NSLog(#"categorylist>>>>>> %#",appdelegate.categoriesList);
}
categoriesArray = [[NSMutableArray alloc]init];
categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"] mutableCopy];
then it not entered into if condition.
and if i try with not equal like this.
if (![[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"]) {
[[NSUserDefaults standardUserDefaults] setObject:appdelegate.categoriesList forKey:#"categories"];
NSLog(#"categorylist>>>>>> %#",appdelegate.categoriesList);
}
categoriesArray = [[NSMutableArray alloc]init];
categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"] mutableCopy];
then enter for every build and run.
But i need this for first build and run i mean at installing time.
can any one please help me.
Thank u in advance.
(let me add comment if any one did n't understand my question)
categoriesArray = [[NSMutableArray alloc]init];
categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"] mutableCopy];
The lines above create a leak: you first allocate one array, and then you immediately assign a different array to the same pointer that was keeping track of the array that you allocated. After the second line, you have no way to release the first array.
As for the main question, I suspect that the check
if (![[NSUserDefaults standardUserDefaults] arrayForKey:#"categories"]) {
succeeds every time because there's never a value written for the key #"categories". I see that the lines inside that conditional block try to write a value, but appdelegate.categoriesList may well be nil.