The Annotation Object Model


This article explains how the PSPDFAnnotation and PSPDF*FormElement classes can be used. To get an overview of the annotation support in PSPDFKit, see Introduction to Annotations.

To learn more about how you can check if annotations have been added/removed/changed, see Detecting if annotations have changed

Changing Annotations

The annotation object model is based on PSPDFModel. Changes need to be made on the main thread. If a PSPDFViewController is currently displaying the PSPDFDocument that owns the annotation, you should emit a change notification to ensure the UI is correctly updated:

Copy
1
2
3
4
let freeTextAnnotation: PSPDFFreeTextAnnotation = ...
freeTextAnnotation.contents = "These are my new note contents"

NotificationCenter.default.post(name: NSNotification.Name.PSPDFAnnotationChanged, object: freeTextAnnotation, userInfo: [PSPDFAnnotationChangedNotificationKeyPathKey: ["contents"]])
Copy
1
2
3
4
5
PSPDFFreeTextAnnotation *freeTextAnnotation = ...;
freeTextAnnotation.contents = @"These are my new note contents";

[NSNotificationCenter.defaultCenter postNotificationName:PSPDFAnnotationChangedNotification
object:freeTextAnnotation userInfo:@{PSPDFAnnotationChangedNotificationKeyPathKey : @[@"contents"]}];

This sends a PSPDFAnnotationChangedNotification. The PSPDFAnnotationChangedNotificationKeyPathKey should match the change you've made - this enables PSPDFKit to perform additional performance optimizations (various properties might not require a new render step, for example).

Deleting Annotations

Deleting annotations should be performed by calling removeAnnotations:options: on your PSPDFDocument. This will emit either a PSPDFAnnotationsRemovedNotification or a PSPDFAnnotationChangedNotification, depending on whether the annotation has been saved in the PDF already - in that case we need to use soft delete to track and correctly update the file.

Thread Safety

Annotations should only be accessed on the main thread. They can be created on any thread, but as soon as they're added to a PSPDFDocument, they need to be treated as main thread accessible only. The annotations will check access via testing if the documentProvider property is set and assert if a non-main-thread access is detected. This behavior is new in PSPDFKit 4.1 to ensure that there won't be situations where the main thread is writing to a model being evaluated on a background thread, which could lead to inconsistencies or even a crash (accessing an already released object, etc.).

Internally, PSPDFKit uses immutable copies to feed the render queue and to ensure thread safety. These methods are not exposed. If the automatic annotation fetching feature is used for document rendering, immutable copies are used to ensure thread safety.

Was this page helpful? We're happy to answer any questions.