I have 3 UIVIewControllers that have NSUsuerDefaults to store data. My 4th UIViewController is used to display the total data collected between the first 3 UIViewControllers. How do I collect the data and display it in a UITextfield? Here is an example of my NSUserDefault code that I'm using:
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue22"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue43"]]; I want to add this collected data to a UITextfield on my 4th UIViewController.
Try this:
textField.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
Or
NSString *storedValue1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
textField.text = storedValue1;
I think you should use
tex setText:[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"];
So basically you need to use valueForKey: in place of objectForKey:
Hope this helps you.
EDIT:
[text setText:[NSString stringWithFormat:#"%# %# %#",[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue1"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue22"]]];
EDIT-2:
UITextField(Total) is Say txtTotal
UITextField(storetext1) is say txtStore1
UITextField(storetext2) is say txtStore2
UITextField(storetext3) is say txtStore3
Now simply do this as
int sum = [txtStore1.text intValue] + [txtStore2.text intValue] + [txtStore3.text intValue]
txtTotal.text = [NSString stringWithFormat:#%d",sum];
Related
This question already has answers here:
Easy way to see saved NSUserDefaults?
(24 answers)
Closed 9 years ago.
I would like to print all values I saved via NSUserDefaults without supplying a specific Key.
Something like printing all values in an array using for loop. Is there a way to do so?
Objective C
all values:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);
all keys:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
all keys and values:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
using for:
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
for(NSString* key in keys){
// your code here
NSLog(#"value: %# forKey: %#",[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}
Swift
all values:
print(UserDefaults.standard.dictionaryRepresentation().values)
all keys:
print(UserDefaults.standard.dictionaryRepresentation().keys)
all keys and values:
print(UserDefaults.standard.dictionaryRepresentation())
You can use:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultAsDic = [defaults dictionaryRepresentation];
NSArray *keyArr = [defaultAsDic allKeys];
for (NSString *key in keyArr)
{
NSLog(#"key [%#] => Value [%#]",key,[defaultAsDic valueForKey:key]);
}
Print only keys
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
Keys and Values
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
You can log all of the contents available to your app using:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
I have an integer high score. But I don't know how save the best of it and show on the screen.
This is my code, thank for your help.
-(void)aggiungiPunti
{
punteggio = punteggio +0001;
[labelPunteggio setString:[NSString stringWithFormat:#"%d", punteggio]];
}
And in the init method:
labelPunteggio = [CCLabelTTF labelWithString:#"0000" fontName:#"Marker Felt" fontSize:13];
labelPunteggio.position = ccp(30, altezzaSchermo -15);
[self addChild:labelPunteggio];
U can do this :
write this code in app delegate:
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"key"]
In the class where the top score is to be displayed :
if([punteggio intValue]>[[[NSUserDefaults standardUserDefaults] valueForKey:#"key"]intValue])
{
//display the score in the desired label
[labelPunteggio setString:[NSString stringWithFormat:#"%d", punteggio]];
// set the new best score in the userDefault
[[NSUserDefaults standardUserDefaults] setInteger:[punteggio intValue] forKey:#"key"];
}
like the Q
i have this code
K1player1D.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoredLabel1"];
K1player1L.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scorelLabel1"];
K1player1K.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scorekLabel1"];
K1player1Q.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoreqLabel1"];
K1player1T.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoretLabel1"];
in viewDidLoad, for four players, so its 16 labels. is there any shorter way/code to do it ?
You could use NSMutableArray fill all the UILabel inside it and in a loop:
int i=1;
for(Player in ArrayOfUILabel){
Player.text = [[NSUserDefaults standardUserDefaults] objectForKey:(#"K1scoredLabel%d",i)];
i++;
}
EDIT
I would place them in an NSDictionary
NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
K1player1D,#"K1scoredLabel1",
K1player1L,#"K1scorelLabel1",
K1player1K,#"K1scorekLabel1",
K1player1Q,#"K1scoreqLabel1",
K1player1T,#"K1scoretLabel1",nil];
for(NSString * key in [playerDict allKeys]){
PlayerObject * player = [playerDict objectForKey:key];
player.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
There is another way to do this using Joels's answer combined with KVC (Key value coding). I don't know if it's a particularly good approach, but I've included it for the sake of completeness:
NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"K1player1D",#"K1scoredLabel1",
#"K1player1L",#"K1scorelLabel1",
#"K1player1K",#"K1scorekLabel1",
#"K1player1Q",#"K1scoreqLabel1",
#"K1player1T",#"K1scoretLabel1",nil];
for(NSString * key in [playerDict allKeys]){
NSString *labelName = [playerDict objectForKey:key];
UILabel *label = [self valueForKey:labelName]; // grab the correct label using KVC
label.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
This could be made simpler if the label names matched the keys in the NSUserDefaults (then you could just use an array of names instead of a dictionary).
I have a UITableView with a UISwitch button in it. I want that when I run my application default value of the UISwitch button should be ON. If I toggle the switch button from on to off the value in the plist should change to OFF. If I quit the app and then I again run my app the value should again default to ON in the plist.
I have tried using NSUserDefaults, it works i.e when I change the value from ON to OFF the value in NSUserDefaults also changes. But when the app is run again the default value is not set to ON.
- (void)viewDidLoad {
[super viewDidLoad];
settings = [[NSMutableArray alloc]initWithObjects:#"Clock",#"Time Format",#"Weather",#"Degrees",nil];
switchControl = [[UISwitch alloc]initWithFrame:CGRectMake(205, 110, 20, 15) ];
[self.switchControl addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:switchControl];
NSString *viewdid = #"ON";
userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:viewdid forKey:#"stateOfSwitch"];
}
- (void)viewWillAppear:(BOOL)animated {
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfSwitch"];
if([_value compare:#"ON"] == NSOrderedSame){
[switchControl setOn:YES animated:YES];
}
else {
[switchControl setOn:NO animated:YES];
}
[super viewWillAppear:animated];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 4;
}
-(void)switchChanged:(id)sender
{
app= (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
NSString *value = #"ON";
userdefaults = [NSUserDefaults standardUserDefaults];
if(!switchControl.on){
value = #"OFF";
[userdefaults setObject:value forKey:#"stateOfSwitch"];
}
[userdefaults setObject:value forKey:#"stateOfSwitch"];
[userdefaults synchronize];
}
//this is my second class where i am accessing my userdefaults key and depending on that hiding the views
- (void) viewWillAppear:(BOOL)animated
{
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfSwitch"];
if([_value compare:#"ON"] == NSOrderedSame){
newview.hidden = NO;
newnewview.hidden =NO;
firstview.hidden = NO;
secondview.hidden = NO;
thirdview.hidden = NO;
}
else if([_value compare:#"OFF"] == NSOrderedSame) {
newview.hidden = YES;
newnewview.hidden= YES;
firstview.hidden = YES;
secondview.hidden = YES;
thirdview.hidden = YES;
}
}
In appDelegate did finish loading write below statements
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
May be you have not dump new values to plist?
Try to call [[NSUserDefaults standardUserDefaults] synchronize]; after setting new value to NSUserDefaults.
Either do
// set when launching the app
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
or
// set when terminating
- (void)applicationWillTerminate:(UIApplication *)application
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Furthermore, you should test your NSString using isEqualToString: as compare: may lead to false positives (e.g. if one of the strings is nil).
You shouldn't store a string, which has the potential for parsing bugs, when NSUserDefaults is perfectly capable of storing BOOLs directly.
Just store it like this:
#define StateOfSwitch #"StateOfSwitch"
-(void)switchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:switchControl.on forKey:StateOfSwitch];
[[NSUserDefaults standardUserDefaults] synchronize];
}
and then later, load the value like this:
switchControl.on = [[NSUserDefaults standardUserDefaults] boolForKey:StateOfSwitch];
(Note it's a good idea to never use string keys directly, it's better to #define them to prevent typo errors. Plus you get command + click to jump to definition, autocompletion, etc.)
I am trying to persist the UISwitch state in my settings view of my application. Basically it is a UITableView and contains a few switches to get the user preferences. The below code explains how the switches are constructed (only one switch construct is given below, others are also constructed the sameway).
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierB] autorelease];
if (syncStartupSwitch) {
syncSwitch.on = YES;
}else {
syncSwitch.on = NO;
}
[syncSwitch addTarget:self action:#selector(syncAtStartup:) forControlEvents:UIControlEventValueChanged];
NSLog(#"Why is this not working%#",(syncSwitch.on ? #"YES" : #"NO"));
[cell.contentView addSubview:syncSwitch];
cell.accessoryView = syncSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.reuseIdentifier = #"Cell1";
}
cell.textLabel.text =cellValue;
return cell;
}
Now, I would like to store the state of the Switches using NSUserDefaults. So in my selector method implementation, I defined the NSUserDefaults like this:
-(void) syncAtStartup:(id)sender {
if ([sender isOn]) {
[[NSUserDefaults standardUserDefaults]
setObject:#"YES" forKey:#"SyncAtStartup"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(#"%#",(syncStartupSwitch ? #"YES" : #"NO"));
}else {
[[NSUserDefaults standardUserDefaults]
setObject:#"NO" forKey:#"SyncAtStartup"];
//syncStartupSwitch = [[NSUserDefaults standardUserDefaults]boolForKey:#"SyncAtStartup"];
}
}
Finally, in my viewDidLoad I wrote this line of code:
syncStartupSwitch = [[NSUserDefaults standardUserDefaults]boolForKey:#"SyncAtStartup"];
I am sure there is some missing logic to my implementation. Can somebody point out the flaw and correct me?
UPDATE:
I took the suggestion from #jfalexvijay and used the below code:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SyncAtStartup"];
BOOL syncStartupSwitch = [[NSUserDefaults standardUserDefaults] boolForKey:#"SyncAtStartup"];
When I look into the Preferences folder, I see the plist getting created with the BOOL value in it. I then try to set the UISwitch state in cellForRowAtIndexPath method like this:
syncSwitch.on = syncStartupSwitch;
I also have this line of code in ApplicationWillTerminate and in the selector itself
[[NSUserDefaults standardUserDefaults]synchronize];
Still, after restarting the application on the simulator or device, the switch state is not restored...
What is my mistake in the above code?
Cheers,
iSee
you can use following code;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SyncAtStartup"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:#"SyncAtStartup"];
if you use following code, it will return YES;
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"SyncAtStartup"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:#"SyncAtStartup"];
Just test above code;
Instead of using setObject:forKey: try using setBool:forKey:.
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"SyncAtStartup"];