「Objective-C」の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.検証
#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; }

IOS

Posted by arkgame