我经常使用NSNotificationCenter
进行这些类型的交互。
在您的数据源中写入以下代码:
#define ABCNotificationName @"ABCNotificationName"
#define ABCNotificationData @"ABCNotificationData"
// ...
[[NSNotificationCenter defaultCenter] postNotificationName:ABCNotificationName object:self userInfo:@{ ABCNotificationData: data }];
在您的视图控制器执行以下操作:
-(void)loadView {
// setup your view
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(datasourceUpdated:) name:ABCNotificationName object:dataSource];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)dataSourceUpdated:(NSNotification*)notification {
id data = notification.userInfo[ABCNotificationData];
// respond to the event
[self.tableView reloadData];
}
请注意,如果你没有任何数据通信回对控制器来说,它变得更加容易。在您的数据源中写入以下代码:
#define ABCNotificationName @"ABCNotificationName"
// ...
[[NSNotificationCenter defaultCenter] postNotificationName:ABCNotificationName object:self];
在您的视图控制器执行以下操作:
-(void)loadView {
// setup your view
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(datasourceUpdated) name:ABCNotificationName object:dataSource];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)dataSourceUpdated {
// respond to the event
[self.tableView reloadData];
}
如果你想保持相关数据的代码独立的,为什么不是你的视图控制器上创建一个类别说'MyTableVC + DataSource'什么的?这会工作吗?或者你真的希望另一个班级成为数据源? – GoodSp33d 2014-10-10 17:02:38
@ GoodSp33d不适用于我,因为我想将不同的数据源插入VC以从不同的端点/核心数据请求获取不同的数据 – hashier 2014-10-11 09:04:39
好吧,您正在寻找重用您的VC。然后按照其他人的建议,创建一个接口(协议)并在通常的表格数据源中调用这些方法。其他类可以在协议中实现这些方法,以便将数据提供给VC – GoodSp33d 2014-10-11 09:21:15