iphone - 更新父 View Controller 的数据源

标签 iphone objective-c ios tableview

我有三个级别的 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/

相关文章:

ios - 垂直滚动时 Collection View 在上方重叠

ios - 在运行时定义枚举以填充 UITableView

ios - 如何从 super View Controller 写入 subview Controller 的导出

ios - Google SignIn SDK通过openIDRealm来获取openID

ios - 如何从音频记录生成签名(类似于 Shazam)

iphone - 如何在自定义 iPhone 应用程序中从垂直 View 旋转到水平 View

iphone - Apple 推送通知、注销应用程序和删除应用程序问题/解决方案

iphone - Objective C -std=c99 用法

objective-c - Objective-C 中的继承属性和综合

ios - 无法确定当前国家/地区代码 : Error Domain=GEOErrorDomain Code=-2 "The operation couldn’ t be completed.(GEOErrorDomain 错误 -2。)”