Prytkov
Prytkov

Reputation: 21

How can I reload tableview in viewDidLoad using delegate?

I have simply TODO list in which there are:

Table view reloads after stop/run compiler. But I need to reload table view in viewDidLoad (not in viewWillAppear/viewDidAppear), using delegation table reloads only after something has changed in managedObjectContext.

How can I do that?

Here is my code (what is wrong in it? Where do I have to put [self.tableView reloadData] in my code, for example?):

 - (void)viewDidLoad {
     [super viewDidLoad];
     self.title = @"Note List";
     self.barButtonAddNote = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                           target:self
                                                                           action:@selector(addNewNote:)];
     [self.navigationItem setRightBarButtonItem:self.barButtonAddNote animated:YES];
     [self reloadTableViewWhenItChanges]; }

 - (void)reloadTableViewWhenItChanges // protocol's method {
     self.addNoteViewController.delegate = self;
     if ([self.managedObjectContext hasChanges])
     {
         NSError *error;
         [self.managedObjectContext save:&error];
     }
     [self fetchData];
     [self.tableView reloadData]; }

 - (void)fetchData {
     NSFetchRequest *request = [[NSFetchRequest alloc]init];
     NSEntityDescription *note = [NSEntityDescription entityForName:@"Note"
 inManagedObjectContext:self.managedObjectContext];
     [request setEntity:note];

     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"task" ascending:YES];
     NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
     [request setSortDescriptors:sortDescriptors];

     NSError *error = nil;
     NSArray *mutableFetchResults = [self.managedObjectContext executeFetchRequest:request error:&error];

     if (mutableFetchResults != nil){
         self.notesArray = [[NSMutableArray alloc] initWithArray:mutableFetchResults];
     } }

Upvotes: 2

Views: 1506

Answers (2)

Himanshu
Himanshu

Reputation: 2842

In Objective C :-

[tableViewName reloadData];

In Swift :-

tableViewName.reloadData()

Make sure you have Configure the delegates with UIViewController through UIStoryboard or By code.

Upvotes: 1

D4ttatraya
D4ttatraya

Reputation: 3412

As mentioned by @eik_cloner, you don't need to reload table view in viewDidLoad because it's done automatically.
If you want to do it manually then you have to call reloadData method of UITableView wherever you want as:

[yourTableView reloadData];

Upvotes: 3

Related Questions