Search code examples
iphonensstringnsdatetableviewnsuserdefaults

NSUserDefaults display date and data in the tableView


In the FirstViewController of my survey app I have NSMutableArray that contains data (strings). I've also created date varibale. Here's code

NSDateFormatter *dateformater=[[NSDateFormatter alloc] init];
[dateformater setDateFormat:@"EEEE,dd MMMM yyyy HH:mm a"];

NSDate *today=[NSDate date];
NSString *currentDate=[dateformater stringFromDate:today];

Now I want with the help of NSUserDefaults save data from the array and also save date variable when the survey has been taken and display it in the SecondViewController's tableview (first user can see date of the survey and then by tapping the date - data from array).

I know how NSUSerDefaults work but I don't know how to put array by date variable to be shown in the SecondViewController. Can anyone help me on that?


Solution

  • In AppDelegate.h file just declare variable...

    NSUserDefaults  *userDefaults;
    NSMutableArray *arrDate;
    

    after...

    In AppDelegate.m Fille in applicationDidFinishLonching: Method

        userDefaults = [NSUserDefaults standardUserDefaults];
        NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:@"arrDate"];
        if (dataRepresentingtblArrayForSearch != nil) {
            NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
            if (oldSavedArray != nil)
                arrDate = [[NSMutableArray alloc] initWithArray:oldSavedArray];
            else
                arrDate = [[NSMutableArray alloc] init];
        } else {
            arrDate = [[NSMutableArray alloc] init];
        }
        [arrDate retain];
    

    after that when you want to insert,update or delete Data from this UserDefaults Use Bellow Code...

    for Delete record from array

    [appDelegate.arrDate removeObjectAtIndex:Index];/// give the integer value instead of Index
        
    

    and this is for add record in array..

    [appDelegate.arrDate addObject:currentDate];///add value or add date here
    

    after in final save this modification in array just archive like bellow..

    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.arrDate];
    [appDelegate.userDefaults setObject:data forKey:@"arrDate"];
    [appDelegate.userDefaults synchronize];