如何用PDFKit移除PDF所有注释?当前方案遇数组迭代修改异常
解决PDFKit遍历删除注释时的异常问题
嘿,这个问题我碰到过!你当前的代码之所以会抛出异常,核心原因就是在遍历page.annotations集合的同时直接修改它——每当你调用removeAnnotation(_:)删除一个注释时,原集合的结构会实时变化,遍历过程的索引就会混乱,最终导致异常。
修正方案:遍历注释的副本而非原集合
我们只需要先把页面的注释集合复制成一个独立的数组副本,然后遍历这个副本去删除原页面的注释,这样原集合的修改就不会影响遍历过程了。修正后的代码如下:
func removeAllAnnotations() { guard let document = document else { return } for pageIndex in 0..<document.pageCount { guard let page = document.page(at: pageIndex) else { continue } // 将原注释集合转为独立的数组副本,避免遍历原集合时的动态修改冲突 guard let annotationsToRemove = page.annotations else { continue } for annotation in annotationsToRemove { page.removeAnnotation(annotation) } } }
可选方案:反向遍历原数组
另外也可以用反向遍历原注释数组的方式来避免问题(从最后一个元素往前删,这样前面的元素索引不会因为删除操作而偏移),代码示例如下:
func removeAllAnnotations() { guard let document = document else { return } for pageIndex in 0..<document.pageCount { guard let page = document.page(at: pageIndex), let annotations = page.annotations else { continue } // 反向遍历,从最后一个注释开始删除 for annotation in annotations.reversed() { page.removeAnnotation(annotation) } } }
两种方法都能解决遍历修改数组的冲突问题,你可以根据自己的习惯选择其中一种。
内容的提问来源于stack exchange,提问作者Ruslan Pitula
相关产品推荐
相关产品推荐

