内存管理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



你可能感兴趣的:(内存管理1retain和release)