dimanche 28 juin 2015

Displaying NSMutable array using User Defaults

I am working on an app that has a mutable array of custom object ToDoItem(kind of morphed the dev example into my own app, will change later). I know its not the best way to do it, but I am using the user defaults to save it. Now, in the commented out code at the top, simply calling "addObject" loads the info into the table view. I don't know the intricacies of how this works, can somebody please explain why nothing is loading to the table view when I load it from user defaults? I am a beginner, so please explain thoroughly. Thank you for any help!

@interface ToDoListTableViewController ()
@property NSMutableArray *toDoItems;

@end

@implementation ToDoListTableViewController
- (void)loadInitialData1 {

   /*
ToDoItem *item1 = [[ToDoItem alloc] init];
item1.location = @"BDK";
item1.total = [[NSNumber alloc] initWithFloat:15.0];
item1.tip = [[NSNumber alloc] initWithFloat:5.567];
item1.percentage = [[NSNumber alloc] initWithFloat:33.0];
[self.toDoItems addObject:item1];
ToDoItem *item2 = [[ToDoItem alloc] init];
item2.location = @"Emrick";
item2.total = [[NSNumber alloc] initWithFloat:10.0];
item2.tip = [[NSNumber alloc] initWithFloat:2.0];
item2.percentage = [[NSNumber alloc] initWithFloat:20.0];
[self.toDoItems addObject:item2];
ToDoItem *item3 = [[ToDoItem alloc] init];
item3.location = @"PPM";
item3.total = [[NSNumber alloc] initWithFloat:20.0];
item3.tip = [[NSNumber alloc] initWithFloat:20.0];
item3.percentage = [[NSNumber alloc] initWithFloat:100.0];
[self.toDoItems addObject:item3];
*/


self.toDoItems = [[[NSUserDefaults standardUserDefaults]objectForKey:@"key"]mutableCopy];

}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue {
AddToDoItemViewController *source = [segue sourceViewController];
ToDoItem *item = source.toDoItem;
if (item != nil) {

    [self.toDoItems addObject:item];
    [self.tableView reloadData];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:self.toDoItems forKey:@"key"];

    [defaults synchronize];

    NSLog(@"Data saved");

    }
}

Aucun commentaire:

Enregistrer un commentaire