gpt4 book ai didi

objective-c - 将 KVO 添加到 UITableViewCell

转载 作者:太空狗 更新时间:2023-10-30 03:21:29 26 4
gpt4 key购买 nike

我有一个自定义的 UITableViewCell,它显示 Person 对象的各种属性(由 Core Data 支持)...一些标签、图像等。我目前强制整个 tableview 在任何属性更改时重新加载,这显然效率不高.我知道使用 KVO,我应该能够将监听器添加到单元格中的标签,以监听 Person 属性的变化。但我不确定如何实现它,也找不到任何示例。

这是我通常在 UITableView 的 cellForRowAtIndexPath 中执行的操作:

    - (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
static NSString *simple = @"CustomCellId";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:simple];

if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

for (id findCell in nib )
{
if ( [findCell isKindOfClass: [CustomCell class]])
{
cell = findCell;
}
}
}
Person *managedObject = [self.someArray objectAtIndex: indexPath.row];
cell.namelabel.text = managedObject.displayName;
return cell;
}

该单元格已连接到 IB。我想检测 displayName 何时更改,并仅更新名称标签。谢谢

最佳答案

上面的答案非常适合静态单元格。将 KVO 用于 UITableViewCell s 仍然适用于单元格重用。在单元格即将出现时添加你需要的观察者,当单元格不再显示时移除它们。唯一的trick是Apple似乎对发送didEndDisplayingCell:不一致,所以在iOS 6.1上需要在两个地方去掉观察者

@implementation MyTableViewCell

@property MyTableViewController * __weak parentTVC;

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
((MyTableViewCell *)cell).parentTVC = self;
// Don't add observers, or the app may crash later when cells are recycled
}


- (void)tableView:(UITableView *)tableView
willDisplayCell:(HKTimelineCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Add observers
}

- (void)tableView:(UITableView *)tableView
didEndDisplayingCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self removeMyKVOObservers];
}

- (void)viewWillDisappear:(BOOL)animated
{
for (MyTableViewCell *cell in self.visibleCells) {
// note! didEndDisplayingCell: isn't sent when the entire controller is going away!
[self removeMyKVOObservers];
}
}

如果不清理观察者,可能会发生以下情况。观察者可能会尝试通知位于该内存位置的任何对象,该位置甚至可能不存在。

<NSKeyValueObservationInfo 0x1d6e4860> (
<NSKeyValueObservance 0x1d4ea9f0: Observer: 0x1d6c9540, Key path: someKeyPath, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x1c5c7e60>
<NSKeyValueObservance 0x1d1bff10: Observer: 0x1d6c9540, Key path: someOtherKeyPath, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x1c588290>)

关于objective-c - 将 KVO 添加到 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com