10-retain和release的简单使用

来源:互联网 发布:手机破解版软件盒子 编辑:程序博客网 时间:2024/05/16 07:09

//  Student.h

//  内存管理1-retainrelease的简单使用

//


#import <Foundation/Foundation.h>


@interface Student : NSObject


@property int age;

@end

==============

//  Student.m

//  内存管理1-retainrelease的简单使用


#import "Student.h"


@implementation Student

@synthesize age = _age// xcode4.5环境下可以省略


- (void)dealloc {

    NSLog(@"%@被销毁了"self);

    

   [super dealloc];

    // 一定要调用superdealloc方法,而且最好放在最后面调用

}

@end

=================

//  main.m

//  内存管理1-retainrelease的简单使用

//


#import <Foundation/Foundation.h>

#import "Student.h"


void test() {

    Student *stu = [[Student allocinit]; // 1

    

    // z代表无符号

    NSLog(@"count:%zi", [stu retainCount]);

    

    [stu retain]; // 2

    

    NSLog(@"count:%zi", [stu retainCount]);

    

    [stu release]; // 1

    

    NSLog(@"count:%zi", [stu retainCount]);

    

    [stu release]; // 0

    

    // [stu release]; // 会发生野指针错误,也就是说访问了不属于你的内存

}


void test1() {

    // Student对象的计数器永远为1,所以不可能被释放

    [[Student allocinit].age = 10;

    

    

    [Student new].age = 10;

    

    // 上面的代码都有内存泄露

}


int main(int argc, const char * argv[])

{

    @autoreleasepool {

        

    }

    return 0;

}

0 0
原创粉丝点击