ios - KVO 在 UITableView 中观察模型变化的最佳实践

标签 ios iphone objective-c uitableview key-value-observing

让我们想象一个基本的 iPhone 应用程序,它有一个显示人员列表的表格 View 和一个用于更改嵌入在导航 Controller 中的人员姓名的详细信息 View 。

我正在使用 KVO 在我的表格 View Controller 中获得通知,即在详细信息 Controller 中更改了一个人的姓名。

我的问题是何时/何处添加和删除我的 TableView Controller 作为 name 的观察者每个人的对象。

我的做法:

@implementation PeopleTableViewController 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    Person *person = ...; // person for index path

    [person addObserver:self forKeyPath:@"name" options:0 context:(__bridge void *)(PERSON_NAME_CTX)];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    Person *person = ...; // person for index path

    [person removeObserver:self forKeyPath:@"name"];

    // This is not called when the view is removed from the hierarchy
    // Can't use viewDidDisappear: because we are using a navigation controller
    // and tableView:willDisplayCell: is not called when we return from the details controller
}

- dealloc {
    // See comment in didEndDisplayingCell:

    for (UITableViewCell *cell in self.tableView.visibleCells) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

        Person *person = ...; // person for index path

        [person removeObserver:self forKeyPath:@"name"];
    }
}

由于导航 Controller ,事情有点棘手,因为 tableView: didEndDisplayingCell从 View 层次结构中删除 View 时不调用。我无法删除 viewWillDisappear: 中的观察者,因为当用户从细节 Controller 返回时,我仍然需要观察人员对象的变化。

删除 dealloc 中的观察者似乎工作。我的问题:这是正确的方法吗?

最佳答案

通常你应该分别在 viewWillAppear/viewWillDisappear 方法上调用 addObserver/removeObserver,因为 dealloc 方法与这个调用不平衡(我的意思是可以比上面的方法调用几次)。也许最好的解决方案之一是使用 NSFetchedResultsController 来跟踪对数据源的任何更改。

关于ios - KVO 在 UITableView 中观察模型变化的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20520753/

相关文章:

objective-c - 当我在 FB 桌面上看到消息时,FB messenger 如何从 iOS 应用程序中删除推送通知?

objective-c - 如何在 Objective-C 中将变量值传递给没有参数的方法?

ios - 仅更改 UITableView 中一个部分的页脚大小

ios - 使用配置文件测试飞行问题

iphone - 设置对象的图层会导致内存问题吗?

objective-c - NSNetService 委托(delegate)未被调用

objective-c - CocoaAPI 转换为 MacRuby API 的规则是什么

javascript - 安装带有转换错误的 fuse.js 时,React-native 应用程序崩溃

iphone - 创建协议(protocol)后访问 UIPageViewController 的委托(delegate)方法

ios - 苹果ios应用程序图标问题