How to save date in nuserdefaults in iPhone? - iphone

I am saving my date selected from datepicker in nuserdefaults. When I select the date from date picker say 9.52 AM and click on the save button the date selected is getting saved in userdefaults and in SQLite. If I select another date to set another alarm say 9.54 AM and click on the save button, both the dates are getting saved in SQLite but the problem is the earlier 9.52 date is getting overrided by 9.54 in nsuserdefaults and so the notification for the last added date in userdefaults is shown.
I want that if I select 9.52AM and then click save and then select 9.54 AM and click save both the time should be saved in userdefaults and the notification for 9.52AM should be shown first.

I think you add date objects to array and than add to NSUserDefaults
if ([[NSUserDefaults standardUserDefaults] valueForKey:#"date"]==nil)
{
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"date"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"date"]);
}
else
{
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:#"date"];
NSMutableArray *array_dates = [[NSMutableArray alloc] init];
for(int i =0;i<[array count];i++)
{
[array_dates addObject:[array objectAtIndex:i]];
}
[array_dates addObject:YourpresentdateObject];
[[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:#"date"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"date"]);
}

If you don't want to override dates than use different keys for both the alarm.

You will have to use different keys when you save the date using NSUserDefaults. Something like-
//Use whatever format you are using to save the date
[[NSUserDefaults standardUserDefaults] setInteger:952 forKey:#"alarm1"];
[[NSUserDefaults standardUserDefaults] setInteger:954 forKey:#"alarm2"];
You are currently using the same key, which is why it overwrites the value.

Related

Saving incremental int variable

I need to save a variable that increments every time a user hits a button within the app. I've been trying to do that with NSUserDefaults with no success. Here's the code I'm using:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
When I output this in the log, however, I keep getting 0.
Any help would be greatly appreciated.
Try adding:
[[NSUserDefaults standardUserDefaults] synchronize];
After each time you change the value of your integer.
Quoting Apple's documentation on synchronize:
Writes any modifications to the persistent domains to disk and updates
all unmodified persistent domains to what is on disk.
http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/synchronize
So with this modification, your final code should look like this:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
EDIT: Actually on second thought, give this a try:
I think the problem is using i++ assumes that the application will always be able to keep track of the count, and every time you re-enter the application i gets reset.
The following works, I just tested it.
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"]) {
[[NSUserDefaults standardUserDefaults] setInteger:i forKey:#"AppCount"];
}else{
[[NSUserDefaults standardUserDefaults] setInteger:[[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"] + 1 forKey:#"AppCount"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
You can use Static NSUIInteger appCount=0;
in the function user taps increase it value appCount++;
that keeps the value in function calls within the app. after app closing you write it to file.
- (void)viewDidLoad {
[super viewDidLoad];
countFirst= [[NSUserDefaults standardUserDefaults]integerForKey:#"Counter"];
countFirst++;
}
Write this wherever you want to increment.
[[NSUserDefaults standardUserDefaults] setInteger:countFirst++ forKey:#"Counter"];

Save an int value, and load then app loads

I'm making an app that changes images every time the user press on the screen. It is using an int to know then to change image.
I need help to save the int value then screen is pressed and load it then the app is loaded.
You could use the NSUserDefaults class for this:
// Write
[[NSUserDefaults standardUserDefaults] setInteger:7615 forKey:#"customIntegerValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Read
NSLog(#"Integer = %i", [[NSUserDefaults standardUserDefaults] integerForKey:#"customIntegerValue"];
// To save in pref
int highScore = yourGameScore;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:#"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
// To get saved value from pref
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:#"HighScore"] intValue ];
You can see similar post here: stackOldPost
You can save values in NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

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!

Detecting the first ever run of an app

I am creating an app in which I have to create a plist when the app launches for the first time. I'm later going to use the plist to store details a user later inputs. How can I detect the first launch of the app? I was experimenting with NSUserDefaults but I think I'm doing something wrong.
You can do this with NSUserDefaults. But be careful with the Version Number.
Do the following:
NSString *bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
NSString *appFirstStartOfVersionKey = [NSString stringWithFormat:#"first_start_%#", bundleVersion];
NSNumber *alreadyStartedOnVersion = [[NSUserDefaults standardUserDefaults] objectForKey:appFirstStartOfVersionKey];
if(!alreadyStartedOnVersion || [alreadyStartedOnVersion boolValue] == NO) {
[self firstStartCode];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:appFirstStartOfVersionKey];
}
the selector firstStartCode will only be called on time for each application version on the very first run.
Okay?
I like to use NSUserDefaults to store an indication of the the first run.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"])
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can then test for it later...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"firstRun"])
{
// do something or not...
}
Taken from: Best way to check if an iPhone app is running for the first time
You can use the following:
-(void) firstLaunch {
//Code goes here
}
-(void) firstLaunchCheck {
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"didLaunchFirstTime"]) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"didLaunchFirstTime"];
[self firstLaunch];
}
}

Save And Load A Single Value, iPhone

I have a feeling there is a simple way to do this. I have a number between 1 and 100 and it is stored in a variable called firstValue. This variable is then put into a UILabel. When the user exits my app, I want this firstValue to be saved so that when the app is loaded by the user this number can be re-inserted into the UILabel (firstValueLabel.text).
Many thanks,
Stuart
You can use NSUserDefaults for this.
To save it:
NSInteger myValue = ...; // This is your number
NSString *key = ... ; // This is a string to identify your number
[[NSUserDefaults standardUserDefaults] setInteger:myValue forKey:key];
To read it:
NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:key];
If no previous value has been saved, the value returned will be 0.
Add this to your applicationWillTerminate:
[[NSUserDefaults standardUserDefaults] synchronize];
you can use the NSUserDefaults to store some variable for your application to retrieve them after a close of the application.
For exemple:
// Set the name of the view
[[NSUserDefaults standardUserDefaults] setInteger:10 forKey:#"firstValue"];
To retrieve the last action of the user:
// Retrieve the last view name
Integer firstValue = [[NSUserDefaults standardUserDefaults] integerForKey:#"firstValue"];
But you can add other than a integer. (see the NSUserDefaults Class Reference)