gpt4 book ai didi

iOS - UITableViewCell dealloc 错误中的自定义 UISwitch

转载 作者:行者123 更新时间:2023-11-29 01:17:21 25 4
gpt4 key购买 nike

我正在使用 UISwitch 子类将 UISwitch 添加到我所有的 UITableViewCells。我使用自定义类能够将更多信息传递给 UISwitch。

我在 iOS 8 上遇到的错误是:

*** -[NamedUISwitch _sendActionsForEvents:withEvent:]: message sent to deallocated instance

NamedUISwitch 是我制作的自定义 UISwitch:

@interface NamedUISwitch : UISwitch
@property (nonatomic, strong) NSString *specialinfo1;
@property (nonatomic, strong) NSString *specialinfo2;
@end

@implementation NamedUISwitch

@end

这就是我在 cellForRowAtIndexPath 方法中实现 UISwitch 的方式。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] init];
NamedUISwitch *switchview = [[NamedUISwitch alloc] initWithFrame:CGRectZero];
[switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
cell.textLabel.text = ...;
switchview.nomEtablissement = ...;
switchview.tag = ...;
switchview.typeInfo = ...;
cell.accessoryView = switchview;
return cell;
}

我曾尝试使用 Instruments 来跟踪 dealloc,但我似乎无法让它以正确的方式工作。我该如何解决这个 dealloc 问题?

最佳答案

您没有正确创建单元格。您需要这样的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
NamedUISwitch *switchview = nil;
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
switchview = [[NamedUISwitch alloc] initWithFrame:CGRectZero];
[switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = switchview;
} else {
switchview = cell.accessoryview;
}

cell.textLabel.text = ...;
switchview.nomEtablissement = ...;
switchview.tag = ...;
switchview.typeInfo = ...;
// You also need to set switchview.on here

return cell;
}

这样您就可以正确地重复使用单元,并且每个单元仅获得一个开关。

更好的选择是创建自定义表格单元格类,并且该单元格类设置自己的开关。

关于iOS - UITableViewCell dealloc 错误中的自定义 UISwitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002662/

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