How to save date in nuserdefaults in 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 c开发者_Python百科lick 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.
精彩评论