[Reading Notes] iOS-memory management, ios-memory management
Cocoa memory management: retain, release and autorelease.
Each object maintains a reserved counter. When an object is created, its reserved counter value is 1; when the object is retained, the reserved counter value is added 1; when the object is released, the reserved counter value is reduced by 1; when the reserved counter value is 0, the object is destroyed. When an object is destroyed, the dealloc method of the object is called first, and the Occupied memory is recycled for other objects.
When an object receives an autorelease message, its reserved counter value does not change immediately. On the contrary, this object is only put into the nutoreleasepool. When the automatic release pool is destroyed, a release message is sent to all objects in the pool. All automatically released objects minus the reserved counter value 1. If the reserved counter value is 0, the object is destroyed. When AppKit is used, Objective-C will create and destroy the automatic release pool for you at the appropriate time, for example, when the current user event is handled. In addition, you need to create your own automatic release pool. The template of the Foundation library tool contains the code.
Three rules on objects and their reserved counters in Cocoa.
1. If you use the new, alloc, or copy operation to obtain an object, the reserved counter value of this object is 1.
2. If an object is obtained through any other method, it is assumed that the reserved counter value of this object is 1 and has been set to automatically released.
3. If an object is retained, the retain method and the release method must be used for the same number of times.
References: Basic Object-C tutorial