OC之【内存管理】


@implementation Student

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


- (void)dealloc {

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

    

   [super dealloc];

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

         否则有一些开发者出现闪退现象,就是把[super dealloc]放到了最前面调用了

}

@end




main.m文件:


void test() {

    Student *stu = [[Student alloc] init]; // 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 alloc] init].age = 10;

    

    

    [Student new].age = 10;

    

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

}


你可能感兴趣的:(ios,内存,Objective-C)