1

I need to remove all annotations from PDF document using PDFKit. Here is my solution:

This solution doesn't work for me, because in one case im getting exception when mutating array while iteration on it.

func removeAllAnnotations() {
        guard let documentCheck = document else { return }
        for i in (0..<documentCheck.pageCount) {
            if let page = documentCheck.page(at: i) {
                for annotation in page.annotations {
                    page.removeAnnotation(annotation)
                }
            }
        }
    }
4

2 回答 2

3

If you want to avoid the “mutate while iterating” problem, just create your own local copy of the array, and iterate through that:

func removeAllAnnotations() {
    guard let document = document else { return }

    for i in 0..<document.pageCount {
        if let page = document.page(at: i) {
            let annotations = page.annotations
            for annotation in annotations {
                page.removeAnnotation(annotation)
            }
        }
    }
}

But, no, I don’t know of any better way to remove all annotations.

于 2019-10-09T16:09:46.027 回答
0

This is the objective-C solution, I came up with. This function will not encounter the “mutate while iterating” crash! Hope this will be helpful to someone.

- (void)removeAllAnnotations {
    if (self.pdfDocument) {
        for (int i = 0; i < self.pdfDocument.pageCount; i++) {
            PDFPage *page = [self.pdfDocument pageAtIndex:i];
            PDFAnnotation *annotation = page.annotations.lastObject;
            while (annotation) {
                [page removeAnnotation:annotation];
                annotation = page.annotations.lastObject;
            }
        }
    }
}
于 2021-11-19T05:18:46.773 回答