RetainedWith

  • @RetainedWith annotation in J2ObjC helps manage reference cycles between parent and child objects, preventing memory leaks when used correctly.

  • It should be used when a parent object can't fully control a child's lifecycle, often because the child is returned to the caller or has the same class as the parent.

  • This annotation applies to specific scenarios with a two-object pair and a direct reference cycle, requiring careful consideration of the child object's behavior and references.

  • Several criteria must be met for @RetainedWith to work as intended, including restrictions on the child's references back to the parent and thread safety during assignment.

  • It's crucial to thoroughly understand the documentation and limitations of @RetainedWith before implementation, and to consider @Weak as a potential alternative when possible.

public abstract @interface RetainedWith implements Annotation

PLEASE READ THIS DOCUMENTATION BEFORE USING THIS ANNOTATION!

Note the criteria listed below which cannot be enforced by static analysis in j2objc. Prefer using Weak over @RetainedWith if possible.

Indicates that the annotated field (child) forms a direct reference cycle with the referring object (parent). Adding this annotation informs J2ObjC of the reference cycle between the pair of objects allowing both objects to be deallocated once there are no external references to either object.

@RetainedWith can be applied when a parent object pairs itself with a child object and cannot fully manage the child's lifecycle, usually because the child is returned to the caller. It can also be applied when the child has the same class as the parent, for example on an inverse field of an invertible collection type.

@RetainedWith can only be applied where there is a two-object pair with a cycle created by one reference from each object. Note: the two references can be from the same declared field. When the references are from different fields only one field should be given a @RetainedWith annotation, and the @RetainedWith field should point from parent to child.

When applied carefully in the right circumstance this annotation is very useful in preventing leaks from certain Java collection types without needing to alter their behavior.

The following criteria must be adhered to otherwise behavior will be undefined:

  • The child object must not reassign any references back to the parent object. Preferably references from child to parent are declared final.
  • The child object must not contain any Weak references back to the parent object.
  • The child object must not be available to other threads at the time of assignment. (Normally, the cycle is created upon construction of the child)

Inherited Method Summary