You should use the
NSPurgeable class when you have objects with bytes that can be discarded when no longer needed. Purging these bytes may be advantageous for your system, because doing so frees up memory needed by other applications. The
NSPurgeable class provides a default implementation of the
NSDiscardable protocol, from which it inherits its interface.
- iOS 4.0+
- macOS 10.6+
- tvOS 9.0+
- watchOS 2.0+
NSPurgeable objects inherit their creation methods from their superclass,
NSPurgeable objects begin "accessed” to ensure that they are not instantly discarded (see
begin method marks the object’s bytes as “accessed,” thus protecting them from being discarded, and must be called before accessing the object, or else an exception will be raised. This method returns
true if the bytes have not been discarded and if they have been successfully marked as “accessed”. Any method that directly or indirectly accesses these bytes or their length when they are not “accessed” will raise an exception. When you are done with the data, call
end to allow them to be discarded in order to quickly free up memory.
You may use these objects by themselves, and do not necessarily have to use them in conjunction with
NSCache to get the purging behavior. The
NSCache class incorporates a caching mechanism with some auto-removal policies to ensure that its memory footprint does not get too large.
NSPurgeable objects should not be used as keys in hashing-based collections, because the value of the bytes pointer can change after every mutation of the data.