vendredi 31 juillet 2015

Saving TextView contents in TableView

I am making a to-do list app and I have a tableview with custom cells in it. The custom cells only have a textview where the user can input their "tasks". Also, the user can add rows for more tasks and delete rows if he/she has completed that task on the list. However if the app is closed the tableview is reset obviously, and the user losses everything he/she has written in the cells before. This way, the app is pretty much useless.

My question is: How could I preserve the text in each cell's TextView even after the app was closed?

EDIT: I managed to save the data in NSUserDefaults by iterating through every cell's textview and getting their text property. However the problem is that if I load the data on startup into an array and populate the cell's textviews from that array in cellForRowAtIndexPath the text in textviews are reset(to the data that was loaded on startup) whenever the user scrolls the tableview as cellForRowAtIndexPath is called again.

So my question is now: How could I overcome this issue? I would only need to populate the tableView on startup not every time cellForRowAtIndexPath is called.

My code:

I wrote a separate method for saving the contents of the cells (notes is just an empty mutable array).

-(void)saveNotes{
   NSArray *cells = [self.tableView visibleCells];
    [notes removeAllObjects];

    for (TableViewCell *cell in cells)
    {
        [notes addObject:cell.textView.text];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:notes forKey:@"notes"];
        [userDefaults synchronize];
        NSLog(@"notes saved!");
    }
}

Than in viewDidLoad I set the tableview's dataSource array to be the one that is stored in NSUserDefaults:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if([userDefaults objectForKey:@"notes"]){
        dataSource = [[userDefaults objectForKey:@"notes"] mutableCopy];
        NSLog(@"Notes loaded");
    }
    else{
        dataSource = [[NSMutableArray alloc]initWithObjects:@"", nil];
        NSLog(@"Nothing found! :(");
    }

After that, in cellForRowAtIndexPath I set the textviews of all the cells to show the text thats was loaded in viewDidLoad:

cell.textView.text = [dataSource objectAtIndex[indexPath row]];

Aucun commentaire:

Enregistrer un commentaire