Manage object lifetimes with AutoreleasePools
masterMethods that do not begin with alloc, new, copy, or mutableCopy typically add the created object to an AutoreleasePool. These objects are released when the pool is drained.
- Main Thread: The pool is typically drained when the thread returns control to the RunLoop (e.g., at the end of a frame).
- Additional Threads: You must create and manage an
AutoreleasePoolfor any additional threads you create to prevent memory leaks. - Extending Lifetime: If you need an autoreleased object to live longer than the current pool's scope, call
retain()on it before the pool is drained. You then become responsible for callingrelease()later.
Debugging Leaks
- Environment Variable: Set
OBJC_DEBUG_MISSING_POOLS=YESto print a runtime warning when an autoreleased object is leaked due to a missing enclosingAutoreleasePoolon its thread. - macOS Tooling: Use
leaks --autoreleasePools <process_id>to view a listing of your program'sAutoreleasePools and their contents.