UILabel text doesn't update after receiving notification - iphone

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

Related

Why Isn't NSUserDefaults working with my UISwitch

I'm trying to setup a UISwitch that is off by default until the user turns it on. However it is showing ON by default now.
AppDelegate's didFinishLaunching:
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"pinCodeSwitch"];
if (!testValue) {
// since no default values have been set, create them here
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"pinCodeSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
VC's viewDidAppear:
UISwitch* testSwitch = [[[UISwitch alloc] init] autorelease];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"]) {
[testSwitch setOn:NO animated:NO];
}
self.pinCodeSwitch = testSwitch;
Method to save BOOL when UISwitch's value changed:
- (IBAction)pinCodeSwitchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"pinCodeSwitch"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"];
}
You're not getting to set the switch since you set 'pinCodeSwitch' to NO. It skips the if statement.
Change it to:
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"])
(Negate your test), then the switch will turn off.
you can specify this value in the Interface Builder by the "STATE" value to OFF.
and after that save the switch value by applying this code:
[YourUiSwitch setOn:NO animated:YES];
[[NSUserDefaults standardUserDefaults]setValue:YourUiSwitch forKey:#"youruiswitch"];
[[NSUserDefaults standardUserDefaults]synchronize];
and when the view did load comes load it from the defaults like this:`YourUiSwitch =
[[NSUserDefaults standardUserDefaults]valueForKey:#"youruiswitch"];`
GOOD LUCK BUDDY!

Saving and displaying data with NSUserDefaults

I've saved some input from a UITextField using the following code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myTextField.text forKey:#"myTextFieldKey"];
[defaults synchronize];
I'd like to display this saved text on a UILabel in another view controller.
I tried this:
myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
but nothing displays. Any help with this would be great. thanks.
Well the loading and saving code is correct, so it looks like the problem is something else.
Try this to debug:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
Now you will see if the value retriever from the NSUserDefaults is set and if the label is assinged.
[[NSUserDefaults standardUserDefaults] setValue:myTextField.text forKey:#"myTextFieldKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
After that use valueForKey not objectForKey:
myLabel.text = [[NSUserDefaults standardUserDefaults] valueForKey:#"myTextFieldKey"];
Try:
myLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"myTextFieldKey"];
Check that myTextField and myLabel aren't nil.

NSUserDefault NSString not getting displayed in label

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;

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

NSUserDefaults problem

I have this in my app delegate applicationDidFinishLaunching method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"AcceptTC"] == nil){
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:#"NO" forKey:#"AcceptTC"];
[defaults registerDefaults:appDefaults];
}
and I have this in my RootViewController viewDidLoad method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if(![defaults boolForKey:#"AcceptTC"]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Notice" message:#"By using this application you agree to be bound by the Terms and Conditions as stated within this application." delegate:self cancelButtonTitle:#"No Deal" otherButtonTitles:#"I Understand",nil];
[alert show];
[alert release];
}
and my alert view delegate does this:
if(buttonIndex == 0){
exit(0);
}
else{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"YES" forKey:#"AcceptTC"];
}
However when I click "I understand" (button index 1) and then restart the application I still see the alert view! Even though I've definiely set the value to YES.
I have no idea how to change this. :( I only want it to show the first time a user starts the application - i don't want to keep showing it every time they want to use it.
Thanks
In my application I'm using NSUserDefaults with a bool, works fine.
When the first ViewController loads, it will do:
BOOL terms = [[NSUserDefaults standardUserDefaults] boolForKey:#"termsaccepted"];
if (!terms) {
[self presentModalViewController:disclaimerViewController animated:YES];
}
Within the disclaimer view, after the button has been tapped:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"termsaccepted"];
[[NSUserDefaults standardUserDefaults] synchronize];
I think you're missing the "synchronize" part. However I find using a bool more streamlined, too.
Maybe you need to call synchronize on the defaults to save the changes to disk?
Concering registerDefaults:
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.
// Load default defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary \
dictionaryWithContentsOfFile:[[NSBundle mainBundle] \
pathForResource:#"Defaults" ofType:#"plist"]]];
Code taken from this SO answer.
Another blog article about NSDefaults:
http://retrodreamer.com/blog/2010/07/slight-change-of-plan/