I noticed whilst playing around today that both the objects below when sent "init" print the same message "_init: TireSnow" to the console. Can anyone shed any light on why this is happening?
// INTERFACE
@interface TireBasic : NSObject {
}
@end
@interface TireSnow : TireBasic {
}
@end
// IMPLEMENT
@implementation TireBasic
- (id) init {
self = [super init];
if(self) {
NSLog(@"TB_init: %@", NSStringFromClass([self class]));
}
return self;
}
- (NSString *) description {
return @"This is a BASIC TIRE.";
}
@end
@implementation TireSnow
- (id) init {
self = [super init];
if(self) {
NSLog(@"TS_init: %@", NSStringFromClass([self class]));
}
return self;
}
- (NSString *) description {
return @"This is a SNOW TIRE.";
}
@end
EDIT2 - Added all of main()
#import <Foundation/Foundation.h>
#import "CarParts.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int tireCount;
CarClass *newCar_001;
EngineClass *newEngine_001;
TireBasic *newTire_BASIC;
TireSnow *newTire_SNOW;
// Setup
NSLog(@"COMPOSITION Start");
newCar_001 = [[CarClass alloc] init];
// Engine
newEngine_001 = [[EngineClass alloc] init];
[newCar_001 setEngine: newEngine_001];
// TIRES (BASIC)
for(tireCount=0; tireCount<2; tireCount++) {
newTire_BASIC = [[TireBasic alloc] init];
[newCar_001 setTire:newTire_BASIC];
[newTire_BASIC release];
}
// TIRES (SNOW)
for(tireCount=0; tireCount<2; tireCount++) {
newTire_SNOW = [[TireSnow alloc] init];
[newCar_001 setTire:newTire_SNOW];
[newTire_SNOW release];
}
// Display
[newCar_001 printCar];
// Clean up
[newCar_001 release];
[newEngine_001 release];
[pool drain];
return 0;
}
OUTPUT
> COMPOSITION Start
> _init: CarClass
> _init: EngineClass
> TB_init: TireBasic
> TB_init: TireBasic
> TB_init: TireSnow *****
> TS_init: TireSnow
> TB_init: TireSnow *****
> TS_init: TireSnow
>
> This is a BASIC TIRE.
> This is a BASIC TIRE.
> This is a SNOW TIRE.
> This is a SNOW TIRE.
>
> _deal: CarClass
> TB_deal: TireBasic
> TB_deal: TireBasic
> TS_deal: TireSnow
> TB_deal: TireSnow ******
> TS_deal: TireSnow
> TB_deal: TireSnow ******
> _deal: EngineClass
The line with stars are coming from the TireSnow [super init] and [super dealloc], it seems to be [self class] that is returning "TireSnow" each time, can anyone explain why?
many thanks
gary
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…