开发者

iphone sdk - reload tableview data - from a separate class

I'd like to run the code [tableView reloadData], except I want to call it from a seperate class to the view controller I want to reload the data in.

(Note. If there is something more effective to reload a tableview than reloadData, chime in).

Say the view I want to reload is 'RootViewController', and I am currently in 'DetailViewController', what do i need to do to make it work.

My best attempt开发者_如何学C right now is [RootViewController.tableView reloadData], but its not right. (I get error: expected ':' before . token.

Regards, @norskben


You can use notifications or a protocol.

Using notifications:

post a notification just after finishing saving the data and before returning from the method. Something like this:

// post notification [[NSNotificationCenter defaultCenter] postNotificationName:@"DataSaved" object:nil];

In the controller handling the table, implement

- (void) dataSaved:(NSNotification *)notification{

    [self.tableView reloadData];

}

and in its viewDidLoad method add the following code to register for notifications:

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

finally, unregister in the dealloc method adding

[[NSNotificationCenter defaultCenter] removeObserver:self];

Using a protocol:

start creating a protocol with a callback that your previous controller can use.

@protocol dataSavedDelegate
-(void)dataSaved;
@end

once you finish saving your data:

[(id< dataSavedDelegate >)object dataSaved];

now, in your previous controller you handle the delegate method: in the dataSaved() method you reload your table.


You need a reference to your RootViewController instance in DetailViewController. Declare a property in DetailViewController and when you instantiate your DetailViewController (from the RootViewController, I assume), set it with something like

// in RootViewController.m
detailController.rootController = self;
[self.navigationController pushViewController:...

Then you can access the root controller from the detail controller:

[self.rootController.tableView reloadData];

Another way is to post a custom NSNotification in DetailViewController when you want the RootController to reload and have the RootController listen for the notification.

Another way is to reload the table only when the user goes back to the root controller (do it in RootViewController's viewWillAppear: method), for why reload a table that isn't even on screen?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜