[Objective-C]OC中的Dealloc方法详解

今天来学习一下Dealloc方法的使用。

它的作用是,当对象的引用计数为0,系统会自动调用dealloc方法,回收内存。它的一般写法:

1:-(void)dealloc{

    [super dealloc];
}
2:-(void)dealloc{
    NSLog(@"laptop dead");
    [_cpu release];
    [super dealloc];
}
(一):为什么需要调用父类的dealloc方法?
     子类的某些对象实例是继承自父类的。因此,我们需要调用父类的dealloc方法,来释放父类
拥有的这些对象。
(二):调用的顺序
     一般说调用的顺序是,当子类的对象释放完时,然后再释放父类的所拥有的实例。这一点与调用初始化方法,
正好相反
下面使用一个例子来演示一下:
1:父类Vehicle.h
#import <Foundation/Foundation.h>

@interface Vehicle : NSObject
{
    @private
    NSString *_name;
}
-(id)initWithName:(NSString *)name;
@end
2:父类Vehicle.m
#import "Vehicle.h"
@implementation Vehicle
-(id)initWithName:(NSString *)name{
    self=[super init];
    if(self){
        _name=[name copy];
    }
    return self;
}
-(void)dealloc{
    NSLog(@"vehicle dead");
    [_name release];
    [super dealloc];
}
@end
3:子类Car.h
#import <Foundation/Foundation.h>
#import "Vehicle.h"
@class Engine;
@interface Car : Vehicle
{
    Engine *_engine;
}
-(void)setEngine:(Engine *)engine;
@end
4:子类Car.m
#import "Car.h"
@implementation Car
-(void)setEngine:(Engine *)engine{
    if(_engine!=engine){
        [_engine release];
        _engine=[engine retain];
    }
}

-(Engine *)engint{
    return  _engine;
}
-(void)dealloc{
    NSLog(@"Car dead");
    [_engine release];
    [super dealloc];
}
@end
5:测试main.m代码
#import <Foundation/Foundation.h>
#import "Engine.h"
#import "Car.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSString *name=[[NSString alloc]initWithFormat:@"audi"];
        Car *car=[[Car alloc]initWithName:name];
        [name release];
        
        Engine *v6=[[Engine alloc]init];
        [car setEngine:v6];
        [v6 release];
        //do something
        [car release];
    }
    return 0;
}
运行截图
[Objective-C]OC中的Dealloc方法详解_第1张图片

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