让我们想象一个基本的 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/