[Objective-C] Dealloc method in OC

Source: Internet
Author: User

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
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.