|
cocoa中的内存管理机制--引用计数

Cocoa中提供了一个机制来实现上面的逻辑模型,它被称为“引用计数”或者“保留计数”。引用计数的数值表示对象有几个“人”在使用它
- 每一个对象都拥有一个引用计数(retain count)当对象被创建的时候,引用计数的值为1当发送retain消息时,该对象的引用计数加1,该对象的引用计数为2当向这个对象发送release消息时,该对象的引用计数减1当一个对象的引用计数为0时,系统自动调用dealloc方法,销毁该对象
下面通过一个实例,来看下怎么样进行增加,减少,引用计数 1:创建Person类,并且覆盖dealloc方法:
#import "Person.h"
@implementation Person
-(void)dealloc{
NSLog(@"person dead");
[super dealloc];
}
@end 2:在main.m方法中进行模拟引用计数
#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;
}

|