Reputation: 9481
I have a ViewController that imports two TableViewControllers.
I have the delegate/datasource methods executing in these subclasses, but is there anyway that the ViewController can tell when the each TableView has executed methods such as the delegate method didSelectRowAtIndexPath or do I have to add methods in each tableviewcontroller for polling if cells had been selected?
Thanks!
Upvotes: 0
Views: 184
Reputation: 16938
You can define your own notifications, e.g. "MyDidSelectRowAtIndexPathNotification", and make your main view controller an observer of this notification:
#define kMyDidSelectNotification @"MyDidSelectRowAtIndexPathNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myDidSelectAction:) name:kMyDidSelectNotification object:nil];
Then, in your implementation of tableView:didSelectRowAtIndexPath
, you can simply trigger this notification for all observers:
[[NSNotificationCenter defaultCenter]
postNotificationName:kMyDidSelectNotification object:nil];
You can see here that you could pass the UITableViewCell
or some other object in the notification, if you need it. Your handler for the notification (myDidSelectAction:
in this case) receives an NSNotification
object which would contain your object passed in the postNotification operation.
While a protocol would also work, it is more complicated to setup, in my view.
Have a look at the docs for Notification Center.
Upvotes: 2
Reputation: 37729
well you can create a @protocol
like this:
@protocol MyChildViewControllerDelegate<NSObject>
@optional
- (void)tablView:(UITableView *)tv didSelectRowInChildViewControllerAtIndexPath:(NSIndexPath*)indexPath;
@end
now make a property of MyChildViewControllerDelegate
in class ChildViewController
and @synthesize
it, like this:
@property(assign, nonatomic) id<MyChildViewControllerDelegate> delegate;
Now when making an instance of ChildViewController
in parent classes assign the delegate by self
like this:
ChildViewController *ch = [[ChildViewController alloc] initWithBlahBlah];
ch.delegate = self;
and implement the MyChildViewControllerDelegate
methods.
now when you receive any UITableViewDelegate
callback in ChildViewController
tell your parent classes through delegates.
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)iPath
{
[delegate tablView:tView didSelectRowInChildViewControllerAtIndexPath:iPath];
}
instead of making your own MyChildViewControllerDelegate
you can use apple provided UITableViewDelegate
too (as you find comfort with).
Hope it helps :)
Upvotes: 2