【Lession 10 OC语言】- 内存管理1

本节内容

一、dealloc方法

当一个对象被销毁释放时,会调用dealloc方法

在Staff类中重写下dealloc方法,记住,最后得调用父亲的dealloc方法,因为父类可能还有些对象有释放

#import "Staff.h"


@implementation Staff

-(void)dealloc{
    NSLog(@"Staff 被销毁");
    [super dealloc];
}

@end
#import <Foundation/Foundation.h>
#import "Staff.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        Staff *staff = [[Staff alloc] init];
        [staff setAge:132];
        NSLog(@"staff count: %lu",[staff retainCount]);//%lu 代表 unsigned long
        [staff release];
    }
    return 0;
}

结果,可看见对象已经被销毁,被销毁是由[staff release]所导致的,因为当前引用计数器为1,release一下就变成0,所以就被销毁了

2014-03-17 16:41:52.949 HellowWord_OC[1930:303] staff count: 1
2014-03-17 16:41:52.951 HellowWord_OC[1930:303] Staff 被销毁

 

 二、retain方法

 1 #import <Foundation/Foundation.h>
 2 #import "Staff.h"
 3 
 4 int main(int argc, const char * argv[])
 5 {
 6     @autoreleasepool {
 7         Staff *staff = [[Staff alloc] init];
 8         [staff setAge:132];
 9         NSLog(@"staff count: %lu",[staff retainCount]);//%lu 代表 unsigned long
10         [staff retain];
11         [staff release];
12     }
13     return 0;
14 }

我们在第10行加个retain,看看结果;

2014-03-17 17:30:42.990 HellowWord_OC[2112:303] staff count: 1

alloc的时候引用计数器为1, retain是将引用计数器+1,release是将引用讲数器减1,所以最后的结果是1,这个对象在程序运行结束后没有被释放,可能存在内存泄露

 

 

 

posted @ 2014-03-17 16:46  Vincent_Guo  阅读(297)  评论(0编辑  收藏  举报