内存管理1retain和release

Student.h:

#import <Foundation/Foundation.h>   @interface Student : NSObject  @property int age;  //默认会生成一个_age属性  @end

Student.m:

#import "Student.h"  @implementation Student //@synthesize age=_age;//xcode4.5中可以不使用synthesise方法,直接在头文件中使用property方法即可 //如果只在m文件中定义而没有在h文件中申明的方法属于privte方法,如果不写类型一般默认是protected方法 -(void)dealloc{  //构造父类的回收方法     NSLog(@"%@被销毁了",self);     NSLog(@"_age %i",_age);     [super dealloc];//一定要调用super的dealloc方法,最好放在最后面调用 } @end

main:

#import <Foundation/Foundation.h> #import "Student.h"  int main(int argc, const char * argv[]) {      @autoreleasepool {         Student *stu=[[[Student alloc] init] autorelease];  //alloc方法计数器为1         [stu retain];//调用一次retain方法计数器加1         NSLog(@"retaincount is %zi",[stu retainCount]);         [stu release];//调用一次release方法计数器减1         NSLog(@"retaincount is %zi",[stu retainCount]);         stu.age=10;         [stu retain];//add 1         //这儿retainCount返回的是Unsigned long 无符号长整形 %z代表无符号         NSLog(@"retaincount is %zi",[stu retainCount]);         NSLog(@"Student age is %i",[stu age]);         [stu release];  //计数器为0就调用dealloc方法     }     return 0; } 

结果:

2013-08-02 14:57:25.342 内存管理1retainrelease[788:303] retaincount is 2

2013-08-02 14:57:25.344 内存管理1retainrelease[788:303] retaincount is 1

2013-08-02 14:57:25.344 内存管理1retainrelease[788:303] retaincount is 2

2013-08-02 14:57:25.344 内存管理1retainrelease[788:303] Student age is 10

2013-08-02 14:57:25.345 内存管理1retainrelease[788:303] <Student: 0x100109a90>被销毁了

2013-08-02 14:57:25.345 内存管理1retainrelease[788:303] _age 10























本文转自蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366576,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值