gpt4 book ai didi

ios - 将 UITableView 行拖动到不同的部分会导致崩溃

转载 作者:行者123 更新时间:2023-11-29 00:07:34 25 4
gpt4 key购买 nike

目前我一直在尝试编写一个 UITableView 父 Controller 来监视它的 tableView 的当前状态。此 tableView 有 2 个部分,我的计划是为每个部分创建一个 NSMutableArray,以反射(reflect)当前布局,以便稍后保存到 NSUserDefaults 页面。它以编辑模式显示,带有允许用户使用 Apple 默认拖动实现的标志

由于未知原因,我在使用当前 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 当一行在同一部分中移动时,我可以保持我的数组井井有条,但即使尝试手动刷新我的行,我也无法解决这个问题。所有的 cell.reuseIdentifier 都是由我提供的并且是独一无二的,所以我相信没有任何类型的编译器误解

方法是这样的

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
if (sourceIndexPath != destinationIndexPath) { //not in the same spot
//same section, different row only, works without issues
if (sourceIndexPath.section == destinationIndexPath.section) {
UITableViewCell * cell = [tableView cellForRowAtIndexPath:sourceIndexPath];
if (destinationIndexPath.section == 0) {
[self.visibleSections removeObject:cell.reuseIdentifier];
[self.visibleSections insertObject:cell.reuseIdentifier atIndex:(int)destinationIndexPath.row];
}
else if (destinationIndexPath.section == 1) {
[self.hiddenSections removeObject:cell.reuseIdentifier];
[self.hiddenSections insertObject:cell.reuseIdentifier atIndex:(int)destinationIndexPath.row];
}
}

//moving to different section
else {
NSString * id = [tableView cellForRowAtIndexPath:sourceIndexPath].reuseIdentifier;
if (id.length != 0) {
//movedf from visible to hidden
if (sourceIndexPath.section == 0) {
[self.visibleSections removeObject:id];
[self.hiddenSections insertObject:id atIndex:(int)destinationIndexPath.row]; //CRASHING HERE
}
//moved from hidden to visible
else {
[self.hiddenSections removeObject:id];
[self.visibleSections insertObject:id atIndex:(int)destinationIndexPath.row]; //CRASHING HERE
}
}
}
}

从记录每一行,我确定崩溃通常似乎是在 -(void)insertObject:atIndex: 上,在某些情况下我尝试了 puttng [tableView begin/endUpdates ] 并且它适用于部分之间的一次拖动,但总是在随后的拖动中崩溃,但它也导致了多个带有不可见行的 UI 错误,这让我认为这不是可行的方法。我尝试异步执行我的数组重新排序,但这也是立即崩溃

最终,我希望能够获得 tableView 当前顺序的表示,以便我可以将其保存到我的 NSUserDefaults 中,以便在将来使用时维护用户所需的顺序,如果有人能解决这个问题,我将不胜感激/跟踪状态的更好方法。谢谢

最佳答案

我不确定我是否理解代码,我遗漏了 hiddenSections/visibleSections 定义,但我认为您遗漏了一些东西(如果我误解了,我深表歉意)。

  1. 重用标识符应该与所有类似的单元相同。这就是为什么它被称为重用。这样,当单元格在滚动时移出 View 时,可以重复使用对象 UITableViewCell 并插入文本值而无需重新创建它。
  2. 您似乎将值(value)存储在重用值(value)中。这样,您可以从一个数组中删除该值并将其添加到另一个数组中。但是,(这是一个很大的猜测),您似乎没有将其存储在任何地方。我希望你做这样的事情:

NSString *temp = [self.visibleSections removeObject:id];
[self.hiddenSections insertObject:temp atIndex:(int) destinationIndexPath.row];

  1. 我认为发生的情况是,在同一部分中,UITableViewCell 的生命周期足够长,足以使其正常工作。但是,当移动到不同的部分时,垃圾收集会释放之前步骤中的单元格。

关于ios - 将 UITableView 行拖动到不同的部分会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47609467/

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