main.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // insert code here...
- NSLog(@"Hello, World!");
- //调用引用计数器 alloc计数器加1
- Person *p = [[Person alloc]init];
- //类型不匹配需要强转int a = (int),或是使用匹配类型NSInteger
- int a = (int)[p retainCount];
- NSInteger b =[p retainCount];
- NSLog(@"p retainCount 1:%d,%ld",a,b);
-
- //发送release引用计数器减一,减为零时,对象回收
- //验证对象是否回收,重写-dealloc
- // [p release];
- //给对象发送一条retain消息,可以使引用计数器值+1(retain方法返回对象本身)
- //当对象被回收时,再发送retain就不对了。
- [p retain];
- b =[p retainCount];
- NSLog(@"p retainCount 2:%d,%ld",a,b);
- [p release];
- [p release];
- b =[p retainCount];
- NSLog(@"p retainCount 3:%d,%ld",a,b);
- }
- return 0;
- }
复制代码
Person.h
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- @end
复制代码
Person.m
- #import "Person.h"
- @implementation Person
- //当一个Person对象被回收时自动调用这个方法
- - (void)dealloc
- {
-
- NSDate *currDate=[NSDate date];//先获取当前时间
- //以下两行是创建一个格式化工具,先初始化一个时间格式,然后定义这个格式
- NSDateFormatter *dateFormate=[[NSDateFormatter alloc]init];
- [dateFormate setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
- //利用上面的时间格式工具把日期转换成字符串对象格式
- NSString *dateStr=[dateFormate stringFromDate:currDate];
-
- NSLog(@"Person 回收了 time:%@",dateStr);
-
- //一定要调用父类的回收方法,而且要放在最后面
- [super dealloc];
- }
- + (void)load
- {
- NSDate *currDate=[NSDate date];//先获取当前时间
- //以下两行是创建一个格式化工具,先初始化一个时间格式,然后定义这个格式
- NSDateFormatter *dateFormate=[[NSDateFormatter alloc]init];
- [dateFormate setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
- //利用上面的时间格式工具把日期转换成字符串对象格式
- NSString *dateStr=[dateFormate stringFromDate:currDate];
-
- NSLog(@"Person load time:%@",dateStr);
- }
- @end
复制代码- 控制台输出:
- 2014-11-09 19:21:44.118 01引用计数器[795:303] Person load time:2014/11/09 19:21:44:110
- 2014-11-09 19:21:44.119 01引用计数器[795:303] Hello, World!
- 2014-11-09 19:21:44.119 01引用计数器[795:303] p retainCount 1:1,1
- 2014-11-09 19:21:44.120 01引用计数器[795:303] p retainCount 2:1,2
- 2014-11-09 19:21:44.121 01引用计数器[795:303] Person 回收了 time:2014/11/09 19:21:44:121
- 2014-11-09 19:21:44.121 01引用计数器[795:303] p retainCount 3:1,1
- Program ended with exit code: 0
复制代码
为什么最后一次输出计数器的时候输出的是1而不是0?????? |