You implement this protocol when a class’s objects have subcomponents that can be discarded when not being used, thereby giving an application a smaller memory footprint.


An NSDiscardable​Content object’s life cycle is dependent upon a “counter” variable. An NSDiscardable​Content object is a purgeable block of memory that keeps track of whether or not it is currently being used by some other object. When this memory is being read, or is still needed, its counter variable will be greater than or equal to 1. When it is not being used, and can be discarded, the counter variable will be equal to 0.

When the counter is equal to 0, the block of memory may be discarded if memory is tight at that point in time. In order to discard the content, call discard​Content​If​Possible() on the object, which will free the associated memory if the counter variable equals 0.

By default, NSDiscardable​Content objects are initialized with their counter equal to 1 to ensure that they are not immediately discarded by the memory-management system. From this point, you must keep track of the counter variable’s state. Calling the begin​Content​Access() method increments the counter variable by 1, thus ensuring that the object will not be discarded. When you no longer need the object, decrement its counter by calling end​Content​Access().

The Foundation framework includes the NSPurgeable​Data class, which provides a default implementation of this protocol.


Accessing Content

func begin​Content​Access()

Returns a Boolean value indicating whether the discardable contents are still available and have been successfully accessed.

func end​Content​Access()

Called if the discardable contents are no longer being accessed.

Discarding Content

func discard​Content​If​Possible()

Called to discard the contents of the receiver if the value of the accessed counter is 0.

func is​Content​Discarded()

Returns a Boolean value indicating whether the content has been discarded.