不务正业之OC(五)-dealloc方法介绍

deallloc方法调用时机:当对象引用计数为0时,销毁对象
首先我们来创建三个类:Compute、Liptop、Cpu。Liptop为Compute的子类。

Compute类定义及实现

//  Compute.h
 
#import <Foundation/Foundation.h>
 
@interface Compute : NSObject{
    NSString * _name; //设置Compute名字
}
- (id) initWithName:(NSString *) name;
 
@end
 
//  Compute.m
 
#import "Compute.h"
 
@implementation Compute
 
- (id) initWithName:(NSString *) name{
    if (self = [super init]) {
        _name = [name retain];
    }
    return self;
}
 
- (void) dealloc{ //重写dealloc方法
    NSLog(@"Compute is broken!");
    [_name release];
    [super dealloc];
}
@end

Liptop定义及实现

//  Liptop.h
 
#import "Compute.h"
 
@class Cpu;
 
@interface Liptop : Compute
{
    Cpu *_cpu;
}
@property (retain) Cpu *_cpu;//实现Liptop的cpu型号
 
@end
 
//  Liptop.m
 
#import "Liptop.h"
 
@implementation Liptop
 
@synthesize _cpu;
 
- (void) dealloc{
    NSLog(@"Liptop is broken!");
    [_cpu release];
    [super dealloc];
}
@end

Cpu定义及实现

//  Cpu.h
 
#import "Liptop.h"
 
@interface Cpu : NSObject
 
@end
 
//  Cpu.m
 
#import "Cpu.h"
 
@implementation Cpu
- (void) dealloc{
    NSLog(@"Cpu is broken!");
    [super dealloc];
}
 
@end

main函数实现

//  main.m
#import <Foundation/Foundation.h>
#import "Compute.h"
#import "Liptop.h"
#import "Cpu.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        //定义新对象liptop_name做为liptop的名字
        NSString *liptop_name = [[NSString alloc] initWithFormat:@"My liptop"];
        Liptop *liptop = [[Liptop alloc] initWithName:liptop_name];
        //释放liptop_name,因为liptop_name所有权给Copmute对象的_name,_name = [name retain],记得一定retain(copy\new也行),不然访问就挂了
        [liptop_name release];
        //设置liptop对象的cpu为intel
        Cpu *intel = [[Cpu alloc] init];
        liptop._cpu = intel;
        //释放intel,对象所有权给_cpu,记得@property (retain) Cpu *_cpu,一定要retain(copy\new也行),不然访问就挂了
        [intel release];
        //释放liptop,调用liptop的dealloc方法,需要把自己的拥有的对象释放掉_cpu,同时调用父类的dealloc方法,来销毁_name对象
        [liptop release];
    }
    return 0;
}

运行结果:
Dealloc[12118:303] Liptop is broken!
Dealloc[12118:303] Cpu is broken!
Dealloc[12118:303] Compute is broken!


Post a Comment