我有三个级别的 ViewController,它们从一个整体类别向下钻取到该类别中的一个主题,再到该主题中的一个引用。
View Controller 被称为:
1 CategoryViewController
2 SubjectViewController
3 QuoteViewController
数据库表“SUBJECT”有类别和主题列。
当我在 SubjectViewController 中时,我可以编辑或删除主题和类别。
我希望能够更新父 View Controller CategoryViewController 的数据源并“刷新”它的 tableView,这样当我导航回它时,我已经看到显示的表格中反射(reflect)的更改。
解决这个问题的正确方法是什么?
最佳答案
我认为委派是完成这项任务最合适的方法。您应该创建一个名为 SubjectViewControllerDelegate
的新协议(protocol)并添加一些方法,例如:
- (void)subjectViewController:(SubjectViewController*)controller didEditSubject:(Subject*)subject;
- (void)subjectViewController:(SubjectViewController*)controller didDeleteSubject:(Subject*)subject;
SubjectViewController 有一个委托(delegate)属性来保持对其委托(delegate)的弱引用。 每当删除或编辑数据时,它都会调用委托(delegate)方法。
CategoryViewController 实现了这个协议(protocol),并在将它推送到导航 Controller 之前将自己设置为 SubjectViewController 实例的委托(delegate)。在此方法中,您可以刷新所有表,或仅更新已更改的行。
更新:
假设您在 CategoryViewController 中只有一个部分并将主题保存在 NSMutableArray
中,您可以使用类似于下面的代码来更新 TableView 的相关部分。
- (void)subjectViewController:(SubjectViewController*)controller didEditSubject:(Subject*)subject{
NSInteger row;
NSIndexPath* indexPath;
NSArray* indexPaths;
row = [self.subjects indexOfObject:subject];
indexPath = [NSIndexPath indexPathForRow:row inSection:0];
indexPaths = [NSArray arrayWithObject:indexPath];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
- (void)subjectViewController:(SubjectViewController*)controller didDeleteSubject:(Subject*)subject{
NSInteger row;
NSIndexPath* indexPath;
NSArray* indexPaths;
row = [self.subjects indexOfObject:subject];
indexPath = [NSIndexPath indexPathForRow:row inSection:0];
indexPaths = [NSArray arrayWithObject:indexPath];
[self.subjects removeObjectAtIndex:row];
[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
关于iphone - 更新父 View Controller 的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135611/