Reputation: 3454
I am trying to understand how updating of a viewController
that is currently visible works.
I have ViewControllerA
and ClassA
. I want to tell ViewControllerA
to reloadData on the tableview
from ClassA
. What is the best way to go about doing this?
I have found this question and answer but I dont think this will work in my situation or I am not understanding it correctly.
Upvotes: 3
Views: 1298
Reputation: 4244
Key value Coding , NSNotificationCentre and Delegates are preferred. But NSNotificationCentre is easiest in your case.
The UIViewController that contains UITableView must add observer like this : Init :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(methodToReloadTable:)
name:@"TABLE_RELOAD"
object:nil];
In delloc method :
[[NSNotificationCenter defaultCenter] removeObserver:self];
Post it from any XYZ class like on any UIButton action :
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TABLE_RELOAD"
object:self];
Advantage of NSNotificationCentre is that they can add observers in multiple classes ..
Upvotes: 1
Reputation: 62686
Answers here about using NSNotificationCenter are good. Be aware of a few other approaches:
A common one is the delegate pattern (see here and here).
Another is that the view controller observes the model change using KVO. (see here and here).
Another good one, often overlooked, which can probably be used in your case is the "do almost nothing" pattern. Just reloadData on your table view when viewWillAppear.
Upvotes: 2
Reputation: 8608
The easiest way without knowing your setup would be to use NSNotificationCenter
. Here is what you could do:
In ViewControllerA
add in hooks for NSNotificationCenter
:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//Register for notification setting the observer to your table and the UITableViewMethod reloadData. So when this NSNotification is received, it tells your UITableView to reloadData
[[NSNotificationCenter defaultCenter] addObserver:self.table selector:@selector(reloadData) name:@"ViewControllerAReloadData" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//Need to remove the listener so it doesn't get notifications when the view isn't visible or unloaded.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Then in ClassA
when you want to tell ViewControllerA to reload data just post the NSNotification
.
- (void)someMethod {
[[NSNotificationCenter defaultCenter] postNotificationName:@"ViewControllerAReloadData" object:nil];
}
Upvotes: 3