Let's learn how to use the Dealloc method today.
When the reference count of an object is 0, the system automatically calls the dealloc method to recycle the memory. Its general syntax:
1:-(void) dealloc {
[super dealloc];}
2:-(void)dealloc{
NSLog(@"laptop dead"); [_cpu release]; [super dealloc]; }
(1): Why do I need to call the dealloc method of the parent class?
Some object instances of the subclass inherit from the parent class. Therefore, we need to call the dealloc method of the parent class to release the parent class.
These objects.
(2): Call Sequence
Generally, the call order is that when the subclass object is released, the instances of the parent class will be released. This is related to calling the initialization method,
Opposite
Here is an example:
1: parent class Vehicle. h
#import
@interface Vehicle : NSObject { @private NSString *_name; } -(id)initWithName:(NSString *)name; @end
2: parent class 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: subclass Car. h
#import
#import "Vehicle.h" @class Engine; @interface Car : Vehicle { Engine *_engine; } -(void)setEngine:(Engine *)engine; @end
4: subclass 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: test the main. m code.
#import
#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; }
Run