Manisha
Manisha

Reputation: 382

Reload TableView from different ViewController using Objective-C

I'm not sure about how to achieve this and hence i'm asking this question.

I have 2 ViewController(VC) named abVC and xyVC. abVC contains only TableView and xyVC contains only a button.

When i tap a button on xyVC, it should reload tableview inside abVC without moving to that abVC.

Is it possible ? If yes.. then please help me,How to do that?

Upvotes: 2

Views: 524

Answers (2)

iOS_MIB
iOS_MIB

Reputation: 1895

You can do it with both block and NSNotification.

With block you can implement it as follows:

make a property as follows in xyzVC.h:

@property(strong,nonatomic)void(^callBack)();

Synthesize this property in xyzVC.m

@synthesize callBack

Call this block in Buttons click event

- (IBAction)btnClick:(UIButton *)sender {

if (callBack)
    {
        callBack();
    }

}

Implement it in abcVC where you want call back:

[abVC setCallBack:^{
        //reload your tableview here
    }];

With NSNotification you can implement it as follows:

Register for receiving notification in abcVC.m

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

- (void)reloadTableView{
  // Reload your tableview here
}

Now post the notification from xyzVC

- (IBAction)btnClick:(UIButton *)sender {

  [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTable" object:nil];

}

Note: If you are using NSNotification then don't forget to remove it when your view controller is dismissed

I hope this will help you :)

Upvotes: 5

Pranav
Pranav

Reputation: 701

  1. Add this line in your button action method

    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTable" object:nil];

  2. Add this code where you have implemented table, so in abVC:

    1. inside viewDidLoad:

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

    1. Add following method

    - (void)reloadTableViewData{
    [self.myTableView reloadData];
    }

    1. Implement dealloc method (to prevent crash)

    - (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ReloadTable" object:nil];
    }

Upvotes: 1

Related Questions