Search code examples
iosdelegatesreloaddata

iOS - reloadData in table from other class


I have read a lot about my problem, I think I need to use delegate, but I have really tried a lot of thing and I am not able to make it work. I am very beginner so I may be missing something essential!

So here is what I have:

I have a split view; on 1 side I have a collectionView and a tableView on the other side. What I want to achieve is to pass datas from the collectionView to the tableView. When I click on one item in the collection, I want it to appear the in the table. So I my table is showing an Array, it works fine, and each time I click on an item in the collection, it adds a dictionary in the Array. This works fine. My problems come when I try to reload the tableView when in the didSelectItemAtIndexPath of the collectionView.

When I create a button in the tableView with an action to [self.tableView reloadData], it works fine. I am just not able to do it from the collectionView.

I have tried : - Can't use reloadData from another class - iOS how to acces [tableView reloadData] from another class

and many more, but not able to make it work.

Thanks for you help,

Ed.


Solution

  • You can use NSNotificationCenter to make calls between the 2 different views. In the TableViewController add the following code to its viewDidLoad method:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveReloadTableViewNotification:)
                                                 name:@"reloadTableViewNotification"
                                               object:nil];
    

    and then add this method further down in your TableViewContoller:

    - (void)receiveReloadTableViewNotification:(NSNotification *) notification
    {
      [self.tableView reloadData];
    }
    

    Now in your CollectionView add this to your button's IBAction:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTableViewNotification"
                                                        object:self];