Memory Management Mechanism in cocoa-reference count
Cocoa provides a mechanism to implement the above logical model, known as "reference count" or "Reserved count ". The value of the reference count indicates that several "persons" of the object are using it.
- Each object has a retain count. when an object is created, the reference count value is 1. When a retain message is sent, the reference count of this object is increased by 1, the reference count of this object is 2. When a release message is sent to this object, the reference count of this object is reduced by 1. When the reference count of an object is 0, the system automatically calls the dealloc method, destroy this object
The following example shows how to increase, decrease, and reference count.
1: Create the Person class and overwrite the dealloc method:
#import "Person.h"@implementation Person-(void)dealloc{ NSLog(@"person dead"); [super dealloc];}@end
2: Simulate reference counting in the main. m METHOD
#import
#import "Person.h"int main(int argc, const char * argv[]){ @autoreleasepool { Person *tom=[[Person alloc]init]; NSLog(@"tom : %ld",[tom retainCount]); [tom retain]; NSLog(@"tom : %ld",[tom retainCount]); [tom release]; NSLog(@"tom : %ld",[tom retainCount]); [tom release]; } return 0;}