5

How would I go about sending a reloadData message to the tableView from a custom tableViewCell?

Brodie
  • 3,526
  • 8
  • 42
  • 61

2 Answers2

10

The easiest way to implement that is to use Delegates.

Define a protocol in your CustomTableCell.h like this:

@protocol CustomTableCellDelegate <NSObject>
@required
- (void)reloadMyTable;
@end

The next step is to provide a delegate var:

@interface CustomTableCell : UITableViewCell {
    id<CustomTableCellDelegate> delegate;
}

@property (assign) id<CustomTableCellDelegate> delegate;

Make shure you synthesize your delegate-Variable in the CustomTableCell.m.

Now you have a Delegate Defined. There are three remaining steps:

When you create your cell you have to set the delegate for this cell like

cell.delegate = self;

Make shure your TableViewController implements your CustomTableCellDelegate. If you do this you will be forced to implement the - (void)reloadMyTable in your TableViewController:

- (void)reloadMyTable {
    [self.tableView reloadData];
}

The last step is to call this method from your CustomTableCell like this:

if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(reloadMyTable)]) {
     [delegate reloadMyTable];
}

More about Delegation here.

In short: You define a protocol in your CustomTableViewCell, which is implemented by the TableViewController. If you send a method-message to your delegate, this message will be send to your TableViewController.

audience
  • 2,412
  • 21
  • 18
  • so far the only thing i'm not clear on is where you say: make sure you r tableviewcontroller implements your custom tablecell delegate. – Brodie Aug 27 '10 at 15:32
  • @audience. Where can I put the code of last step? I mean in which method it should be call – Gajendra K Chauhan Aug 08 '13 at 06:28
  • Whenever you want to reload your table. E.g. when a button is pressed -(IBAction)touchedButton:(UIButton *)sender method – audience Aug 10 '13 at 16:36
2

The best way it's create notification. In your tableView you must create it. It's very easy, something like this:

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

Then you must create method:

- (void)reloadTableView:(NSNotification *)notif {
        [self.yourTableName reloadData];

}

and don't forget delete notification:

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

}

and in your custom tableViewCell when you want reload table you need:

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